【发布时间】:2023-03-10 04:38:01
【问题描述】:
我一直在做一些 Python,但我意识到我实际上对属性装饰器并没有太多了解,所以我尝试做一个简单的例子。这是我使用的代码:
class foo():
def __init__(self):
self.__test = 0
@property
def test(self):
return self.__test
@test.setter
def test(self, value):
self.__test = value
@test.getter
def test(self):
self.__test += 1
return self.__test
然后我开始在交互式 shell 中使用它:
>>> bar = foo()
>>> bar.test
1
>>> bar.test
2
到目前为止,该对象的行为符合我的预期。
然后我尝试检查 setter 方法
>>> bar.test = 5
>>> bar.test
5
>>> bar.test
5
很奇怪。由于某种原因,__test 的值没有增加。
>>> bar._foo__test
2
我以为我已将 __test 设置为等于 5。
发生了什么事?
【问题讨论】:
标签: python python-2.x