我应该使用属性还是私有属性?

Ste*_*ven 3 python

假设我创建了一个类:

class SomeClass:    
    def __init__(self, some_attribute):
        self._attribute = some_attribute

    @property
    def attribute(self):
        return self._attribute
Run Code Online (Sandbox Code Playgroud)

然后,我new_method向我的对象添加一个方法,该方法将使用"属性".因此,我应该使用self._attributeself.attribute?:

def new_method(self):
    DoSomething(self.attribute) # or     DoSomething(self._attribute)
Run Code Online (Sandbox Code Playgroud)

它会产生任何影响或差异吗?

tim*_*geb 6

使用self.attribute将触发调用SomeClass.attribute.__get__,因此会带来更多开销.

使用self._attribute带来的开销较少,但只要在定义中添加有意义的逻辑,就会在代码中引入错误attribute.

在我看来,使用self.attribute一致.如果getter成为瓶颈,请在使用之前考虑缓存策略,_attributeattribute在类内部考虑不一致.你迟早会介绍一个bug.