【发布时间】:2020-03-12 02:30:33
【问题描述】:
我试图弄清楚len() 在使用 inside Python 类时是如何工作的。运行此代码会导致显示的错误,即使我添加了 __len__ 重载并使用了 @property,遵循来自 Internet 的各种建议。
class Routes:
def __init__(self):
self._route_list = list()
def __len__(self):
return len(self._route_list)
@property
def route_list(self):
return self._route_list
@classmethod
def check_list(self):
if not self.route_list or len(self.route_list) == 0:
print('ERROR: no items to print!')
routes = Routes()
routes.check_list()
TypeError: object of type 'property' has no len()
【问题讨论】:
-
“问题”是
@classmethod装饰器 - 删除它,您的代码将正常工作。你为什么首先将方法设为类方法?只有类实例可以访问_route_list -
另外,看起来你的 if 子句
not self.route_list和len(self.route_list) == 0正在检查同样的事情。 -
@MikeScotty 我虽然
@classmethod和@staticmethod就像 C 中的非静态和静态方法。看起来这两个装饰器都是静态方法的变体,它们的缺失意味着该方法是非静态的。
标签: python magic-methods