我目前正在学习OOP,并且我创建了一个存储字典作为变量的类self.foo
。我创建了一个方法bar
返回self.foo
:Python - 返回类变量的最佳做法是什么?
class FooBar:
def __init__(self):
self.foo = {}
def bar(self):
return self.foo
if __name__ == '__main__':
FooBar()
我的问题是这样的。直接调用类变量并使用bar
方法产生相同的结果,这是访问self.foo
的正确方法,还是没有什么区别?
下面是一些例子:
>>>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}'
“这是访问self.foo的正确方法” - 取决于类的用途以及它如何记录。 – khelwood
您可能想了解一下'@ property'装饰器:https://stackoverflow.com/a/17330273/295246 –