-2

For the sake of the example, let's say I have a basic LED class that can blink different patterns on an LED. The LED would have a few attributes describing it's state at any given point in time such as blink pattern, color, current state. Let's also say there are few other attributes that are used by the class for things like timers, pattern counters/iterators, etc.

I want the consumer of the LED class to be able to ask it for it's state info which would include the first list of attributes but not the second.

My question is could someone explain the best practices for storing and returning this kind of state information?

Some thoughts:

  • I would think we want all these attributes to be private since we want others to interact with the LED class through a known API
  • I would want to be able to return all the common state variables in a single "get_state()" call rather than having to access each individually
  • Is there any benefit to having a logical grouping to these attributes in the class or do I just declare each individual one in the constructor?

I'm coming from a C background and trying to stop thinking in structs and do things the Python way.

Otus
  • 305
  • 1
  • 5
  • 16
  • 2
    in python there is no concept of public, private or protected, it is comman practice to use `_` to define a private or protected one, https://docs.python-guide.org/ this will help yu to understand some common pratice in python – sahasrara62 Oct 28 '20 at 20:36
  • Does this answer your question? [Does Python have “private” variables in classes?](https://stackoverflow.com/questions/1641219/does-python-have-private-variables-in-classes) – mkrieger1 Oct 28 '20 at 20:46

1 Answers1

0

You can make the attribute you want private by prefixing it with two underscores. Then, you can provide access to that attribute using the property decorator (basically a getter):

class LEDStuff:

def __init__(self, led_stat):
    self.__led_stat = led_stat  # behind the scene, name mangling happens

@property
def led_stat():
    return self.__led_stat

Note that in python prefixing an attribute with two underscores does not make it private in the sense that an attribute is made private in java. It merely protects the attribute from accidental overriding.

In the python world, it's more common to prefix the attributes we want to protect from accidental overriding with one single leading underscore.

Amir Afianian
  • 2,679
  • 4
  • 22
  • 46