小编典典

不调用属性装饰器的setter方法

python

我正在尝试使用属性方法来设置具有以下类定义的类实例的状态:

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"

我究竟做错了什么?


阅读 130

收藏
2021-01-20

共1个答案

小编典典

在Python 2上, 必须 继承自object才能使属性起作用:

class Result(object):

使它成为一种新型的类。进行此更改后,您的代码将起作用:

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