属性装饰器的setter方法未被调用 [英] setter method of property decorator not being called

查看:130
本文介绍了属性装饰器的setter方法未被调用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

  class结果:
def __init __(self,x = None,y = None):
self.x = float(x)
self.y = float(y)
self ._visible = False
self._status =你看不到我

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

@ visible.setter
def visible(self,value):
如果value == True:
如果self.x不是None,self.y不是None :
self._visible = True
self._status =你可以看到我!
else:
self._visible = False
raise ValueError(不能显示没有x和y坐标的标记。)
else:
self._visible = False
self._status =你看不到我

def currentStatus(self):
return self._status



从结果看,尽管内部变量正在更改,但似乎setter方法没有被执行:

 >>> res = Result(5,6)
>>> res.visible
False
>>>> res.currentStatus()
你看不到我
>>> res.visible = True
>>>> res.visible
True
>>>> res.currentStatus()
你看不到我

错误?

解决方案

在Python 2上,您必须继承 object 属性工作:

  class Result(object):

使它成为一个新式类。有了这个更改,您的代码就可以工作了:

 >> res = Result(5,6)
>>> res.visible
False
>>>> res.visible = True
>>>> res.currentStatus()
'你可以看到我!'


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?

解决方案

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!'

这篇关于属性装饰器的setter方法未被调用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆