我想知道是否有人知道使用 @property
和常规属性是否存在细微差别?
在Python中使用@property
装饰器时,属性初始化时是否可能出现任何问题?
据我了解,这个装饰器允许每次调用函数时都计算一个属性,因为它是一个依赖于其他可变属性的属性。
我已经编写了一些 @property
装饰器,但由于某种原因它们无法工作。
我收到这种形式的错误:
temp_spectra.overall_properties_dictionary 中的键:
属性错误:“Spectra”对象没有属性“overall_properties_dictionary”
据我了解,创建这些@property
的正确方法如下:
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))
但是,这有效!所以我不确定我的代码的哪一部分可能导致此问题。
值得一提的是,我正在转换我的代码以利用多处理
。这会导致问题吗?我只是不明白初始化可能出了什么问题导致这种类型的错误。
编辑:我更改了代码以匹配建议的新样式类。*
最佳答案
值得注意的是,属性仅支持新样式类,而您的类则不支持。
改变
class someObject:
至
class someObject(object):
关于python - python中的属性装饰器初始化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15663366/