【发布时间】:2013-03-17 19:12:54
【问题描述】:
我想知道是否有人知道使用 @property 和常规属性是否有任何细微差别?
在 python 中使用@property 装饰器时,属性初始化是否会出现任何问题?
我的理解是,这个装饰器允许在每次调用它时由函数计算一个属性,因为它是一个依赖于其他可变属性的属性。
我已经写了一些@property 装饰器,但由于某种原因它们没有工作。
我收到这种形式的错误:
for key in temp_spectra.overall_properties_dictionary:
AttributeError: 'Spectra' object has no attribute 'overall_properties_dictionary'
据我了解,创建这些@propertys 的正确方法是这样的:
from PyQt4 import QtCore, QtGui
class someObject(QtCore.QObject):
def __init__(self, x, y):
self.x = x
self.y = y
@property
def some_other_property(self):
# some complicated function which will recalculate everytime it is called
# because the other properties may be mutable
p = self.x + self.y
return p
class otherObject(QtGui.QTabWidget):
def __init__(self, someObject):
print someObject.some_other_property
otherObject(someObject(1,5))
但是,这行得通!所以我不确定我的代码的哪一部分可能导致这种情况。
值得一提的是,我正在将我的代码转换为使用multiprocessing。这会导致问题吗?我只是不明白初始化可能出现什么问题导致这种类型的错误。
编辑:我按照建议更改了代码以匹配新样式类。*
【问题讨论】:
-
@property属性不规则。
标签: python properties decorator dependency-properties