Which of these is the best practice for accessing a variable in a class?

Viewed 121

If I have an object, and within that object I've defined a variable, which of these methods would be considered 'best' for accessing the variable?

Method One

Using a getter function

class MyClass:
    def __init__(self):
        self.the_variable = 21 * 2

    def get_the_variable(self):
        return self.the_variable

if __name__ == "__main__"
    a = MyClass()
    print(a.get_the_variable())

Method Two

Using the @property decorator

class MyClass:

    def __init__(self):
        self._the_variable = 21 * 2

    @property
    def the_variable(self):
        return self._the_variable

if __name__ == "__main__"
    a = MyClass()
    print(a.the_variable)

Method Three

Simply accessing it directly

class MyClass:
    def __init__(self):
        self.the_variable = 21 * 2

if __name__ == "__main__"
    a = MyClass()
    print(a.the_variable)

Are any of these methods more pythonic than the others?

2 Answers

Method 3 is the standard pythonic way to start. If you need additional logic, filtering or some other behavior for the attribute you can always go back and add a method for the attribute and use the @property decorator at a later time. That's the beauty of python, start with something simple that works. If you later need finer control over the attribute you can create the property and not have to update/change any of the client code that uses the attribute. The client code will not know the difference between accessing the attribute directly vs calling a method and as a result does not have to change.

This ideology is confirmed via PEP 549

Python's descriptor protocol guides programmers towards elegant API design. If your class supports a data-like member, and you might someday need to run code when changing the member's value, you're encouraged to simply declare it as a simple data member of the class for now. If in the future you do need to run code, you can change it to a "property", and happily the API doesn't change.

I think it's not easy to answer since it's based on the program.

class MyClass:
  def __init__(self):
      self.the_variable = 21 * 2

  def get_the_variable(self):
      return self.the_variable

But if you want to pass a class attirubete to some variable, I think it's better to use getter-setter, since it is more readable and understandable. Because you are basically telling I ask this value. For example:

if __name__ == "__main__":
  a = MyClass()

  modified_variable = a.get_the_variable() * 2

In contrary, if you are just using that class attribute, third option a.the_variable is better.

if a.get_the_variable() == 42:
   # do something
else:
   # do something
Related