简体   繁体   中英

property decorator initialization in python

I was wondering if anyone knew if there are any subtle differences in using @property and a regular property?

Are there any problems that may occur with initialization for a property when using the @property decorator in python? 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. 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:

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 . 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):

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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