Python - what is the best practise for returning a class variable?

Viewed 88

I am currently learning OOP and I have created a class that stores a dict as a variable self.foo. I have 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 this. Calling the class variable directly and using the bar method produce the same results, which is the correct method for accessing self.foo or doesn't it make a difference?

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}'
2 Answers
Related