在调试一些代码时,我发现使用@property装饰器时出现了意外的行为。简化版如下:
class TestClass:
@property
def __len__(self):
return 6
test_instance = TestClass()
print(len(test_instance))我原本希望输出6,但是我得到了一个TypeError:TypeError: 'int' object is not callable
在没有属性装饰器的情况下,它可以正常工作。我也可以print(test_instance.__len__)没有问题。我正在努力弄清楚为什么会出现这种情况,并希望有人能用简单的术语解释一下。
Edit:对于非dunder方法,这也是我所期望的:
class TestClass:
@property
def foobar(self):
return 6
test_instance = TestClass()
print(test_instance.foobar)6如预期的那样打印。我的理解是,len(Class)是调用__len__方法的语法糖,这就是我在这里感到困惑的原因
发布于 2021-10-07 14:57:13
len尝试调用test_instance.__len__,但现在它是一个属性,该属性access的计算结果是6,而不是函数。
如果您只是想让TestClass实例的硬编码长度为6,那么就不要使用属性。
class TestClass:
def __len__(self):
return 6https://stackoverflow.com/questions/69483263
复制相似问题