[英]property decorator initialization in python
I was wondering if anyone knew if there are any subtle differences in using @property
and a regular property? 我想知道是否有人知道使用
@property
和常规属性是否存在细微差别?
Are there any problems that may occur with initialization for a property when using the @property
decorator in python? 在python中使用
@property
装饰器时,属性初始化可能会出现任何问题吗? It is my understanding that this decorator allows for a property to be calculated by a function everytime it is called since it is a property which depends on other mutable properties. 据我了解,此修饰符允许每次调用函数时都可以计算该属性,因为它是一个依赖于其他可变属性的属性。 I have written some of these
@property
decorators in, but they are not working for some reason. 我已经在其中写了一些
@property
装饰器,但是由于某些原因它们没有起作用。 I recieve this form of an error: 我收到这种形式的错误:
for key in temp_spectra.overall_properties_dictionary:
AttributeError: 'Spectra' object has no attribute 'overall_properties_dictionary'
As I understand it, the correct way for creating these @property
s is like so: 据我了解,创建这些
@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))
However, this works! 但是,这有效! So I'm not certain which part of my code could be causing this.
因此,我不确定代码的哪一部分可能导致此问题。
It is worth mentioning that I am in the process of converting my code to utilize multiprocessing
. 值得一提的是,我正在转换我的代码以利用
multiprocessing
。 Could this cause problems? 这会引起问题吗? I just don't understand what could be going wrong with the initialization to cause this type of error.
我只是不明白初始化会导致这种类型的错误的原因。
EDIT: I changed the code to match the new-style class as suggested.* 编辑:我更改了代码以匹配建议的新样式类。*
One thing worth noting is that properties are only supported for new-style classes, which yours isn't. 值得注意的是,新类仅支持属性,而新类则不支持。
Change 更改
class someObject:
to 至
class someObject(object):
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.