Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/327.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 未调用属性装饰器的setter方法_Python_Class_Properties_Decorator_Python Decorators - Fatal编程技术网

Python 未调用属性装饰器的setter方法

Python 未调用属性装饰器的setter方法,python,class,properties,decorator,python-decorators,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):

我尝试使用属性方法设置类实例的状态,并使用以下类定义:

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"
我做错了什么?

在Python 2上,必须从
对象继承属性才能工作:

class Result(object):
使之成为一门新型的课程。通过该更改,您的代码可以正常工作:

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