setter method of property decorator not being called

試著忘記壹切 提交于 2019-12-19 06:03:25

问题


I am trying to use a property method to set the status of a class instance, with the following class definition:

class Result:
    def __init__(self,x=None,y=None):
        self.x = float(x)
        self.y = float(y)
        self._visible = False
        self._status = "You can't see me"

    @property
    def visible(self):
        return self._visible

    @visible.setter
    def visible(self,value):
        if value == True:
            if self.x is not None and self.y is not None:
                self._visible = True
                self._status = "You can see me!"
            else:
                self._visible = False
                raise ValueError("Can't show marker without x and y coordinates.")
        else:
            self._visible = False
            self._status = "You can't see me"

    def currentStatus(self):
        return self._status

From the results though, it seems that the setter method is not being executed, although the internal variable is being changed:

>>> res = Result(5,6)
>>> res.visible
False
>>> res.currentStatus()
"You can't see me"
>>> res.visible = True
>>> res.visible
True
>>> res.currentStatus()
"You can't see me"

What am I doing wrong?


回答1:


On Python 2, you must inherit from object for properties to work:

class Result(object):

to make it a new-style class. With that change your code works:

>>> res = Result(5,6)
>>> res.visible
False
>>> res.visible = True
>>> res.currentStatus()
'You can see me!'


来源:https://stackoverflow.com/questions/15338659/setter-method-of-property-decorator-not-being-called

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!