python使__magic__方法作为类方法

时间:2019-03-27 11:08:51

标签: python-3.x static-methods

我希望使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)

1 个答案:

答案 0 :(得分:0)

在网上进行了更多搜索之后,我找到了问题here的答案 这个问题是重复的