繁体   English   中英

python中的属性装饰器初始化

[英]property decorator initialization in python

我想知道是否有人知道使用@property和常规属性是否存在细微差别?

在python中使用@property装饰器时,属性初始化可能会出现任何问题吗? 据我了解,此修饰符允许每次调用函数时都可以计算该属性,因为它是一个依赖于其他可变属性的属性。 我已经在其中写了一些@property装饰器,但是由于某些原因它们没有起作用。 我收到这种形式的错误:

for key in temp_spectra.overall_properties_dictionary:

AttributeError: 'Spectra' object has no attribute '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))

但是,这有效! 因此,我不确定代码的哪一部分可能导致此问题。
值得一提的是,我正在转换我的代码以利用multiprocessing 这会引起问题吗? 我只是不明白初始化会导致这种类型的错误的原因。

编辑:我更改了代码以匹配建议的新样式类。*

值得注意的是,新类仅支持属性,而新类则不支持。

更改

class someObject:

class someObject(object):

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM