python将__magic__方法作为classmethod [复制]

问题描述 投票:0回答:1

我想让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)时更具可读性

python-3.x static-methods
1个回答
0
投票

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

© www.soinside.com 2019 - 2024. All rights reserved.