gpt4 book ai didi

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

转载 作者:太空狗 更新时间:2023-10-29 20:38:54 26 4
gpt4 key购买 nike

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

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 上,您必须object 继承才能使属性起作用:

class Result(object):

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

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

关于python - 未调用属性装饰器的 setter 方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15338659/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com