我想让python __magic__
可以访问而无需创建一个类来激活它们
例如
class Group:
_groups = []
# a static var
@classmethod
def __len__(cls):
return len(cls._groups)
# return the len of the static var
但是当我跑的时候
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: object of type 'type' has no len()
为了使它工作我需要键入Group.__len__()
但是这不是一个神奇的方法,这只是一个长名称的函数
为什么我想要它
它使我的代码在将来接受写len(Group._groups)
时更具可读性
在网上搜索后我找到了here问题的答案,这个问题是重复的