不调用属性修饰符的setter方法

时间:2013-03-11 12:32:48

标签: python class properties decorator python-decorators

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

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"

我做错了什么?

1 个答案:

答案 0 :(得分:19)

在Python 2上,必须继承object才能使属性正常工作:

class Result(object):

使它成为一种新式的课程。通过该更改,您的代码可以正常运行:

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