物业装饰的setter方法不会被调用(setter method of property decor

2019-07-21 07:59发布

我试图用一个属性的方法来设置一个类实例的状态,用下面的类定义:

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

从结果来看,虽然,它似乎没有被执行的setter方法,虽然内部变量被改变:

>>> 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"

我究竟做错了什么?

Answer 1:

在Python 2中,你必须继承object的属性来工作:

class Result(object):

使之成为新式类。 与该改变你的代码的工作:

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


文章来源: setter method of property decorator not being called