假设我创建一个类:
class SomeClass:
def __init__(self, some_attribute):
self._attribute = some_attribute
@property
def attribute(self):
return self._attribute
然后,我向我的对象添加一个方法“ new_method
”,该方法将使用“属性”。
因此,我应该使用self._attribute
还是self.attribute
?:
def new_method(self):
DoSomething(self.attribute) # or DoSomething(self._attribute)
它会产生影响或差异吗?
答案 0 :(得分:6)
使用self.attribute
将触发对SomeClass.attribute.__get__
的调用,因此会产生更多开销。
使用self._attribute
的开销较小,但是一旦向attribute
的定义添加有意义的逻辑,就会在代码中引入错误。
我认为请始终使用self.attribute
。如果getter成为瓶颈,请在类内部不一致地使用_attribute
和attribute
之前考虑高速缓存策略。迟早您会引入一个错误。
答案 1 :(得分:3)
我个人的看法是使用self.attribute
。原因是它的实施方式可能会发生变化。
此处将其存储为另一个实例变量,但无论出于何种原因,以后都可以将其存储在基础对象中。
与直接访问相比,这种实现方式的开销当然较小。