簡體   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