What is the best practice for returning a class variable?

I am currently learning OOP and I have created a class that stores a dict as a variable self.foo

. I created a method bar

that returns self.foo

:

class FooBar:

    def __init__(self):
        self.foo = {}

    def bar(self):
        return self.foo


if __name__ == '__main__':
    FooBar()

      

My question is that. Calling a class variable directly and using a method bar

gives the same results, what is the correct method to access self.foo

or doesn't matter?

Here are some examples:

>>>test = FooBar()
>>>test.foo['test'] = 'This is a test'
>>>print(test.foo)
'{'test': 'This is a test'}'

>>>test.bar()['test_2'] = 42
>>>print(test.bar())
'{'test': 'This is a test', 'test_2': 42}'

      

+3


source to share


2 answers


Both are correct, and it doesn't really matter which one you choose. The method approach bar(self)

is the classic "getter" approach, which is often used in other OO languages ​​to access normally private members, but as in python, every member is public by default, it doesn't matter if you use your getter method bar(self)

or call the foo element directly.

Alternatively, you can also use a decorator for the getter method @property

if you want to access an element foo

with a different name. But if you don't need to do anything with the member foo

before accessing it and returning it with a different name, you can also just add a reference to the member foo

as self.bar = self.foo

in your constructor so that you can access the member under a different name. (I think to overdo it with creating a method or just use a property to access a member under a different name, I would use a member reference, but that's my personal preference).



However, if you want to point out that a member should be treated as private and should only be changed within the class or using a setter method, it is common practice to start the member name with _

, for example, in _foo

.

+2


source


You should always use a decorator property

.

If you directly return a variable from a function, then this is wrong, the reader might think that there will be some calculations or modifications in the called function, but in reality you are just passing the variable, so the property decorator will give a clearer context for the reader.

class FooBar:

    def __init__(self):
        self.foo = {}
    @property
    def bar(self):
        return self.foo

      



Then access it,

>>>test = FooBar()
>>>test.foo['test'] = 'This is a test'
>>>print(test.foo)
'{'test': 'This is a test'}'

>>>test.bar['test_2'] = 42
>>>print(test.bar)
'{'test': 'This is a test', 'test_2': 42}'

      

0


source







All Articles