python中的staticmethod和classmethod是不可调用的吗?

2024-04-20 13:22:44 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在编写一个元类来强制类和实例方法的docstring。让我惊讶的是staticmethod和classmethod不像instance方法callable。我不知道为什么?在

class MyMeta(type):
    def __new__(cls, name, parents, attrs):
        print(cls, name, parents, attrs)

        if "__doc__" not in attrs:
            raise TypeError("Please define class level doc string!!!")

        for key, value in attrs.items():
            if callable(value) and value.__doc__ is None:
                raise TypeError("Please define def level doc string!!!")

        return super().__new__(cls, name, parents, attrs)

class A(metaclass=MyMeta):
    """This is API doc string"""
    def hello(self):
        """"""
        pass

    def __init__(self):
        """__init__ Method"""
        pass

    @classmethod
    def abc(cls):
        pass

我不明白为什么他们不能打电话?如果我不为它们定义docstring,它们似乎通过了我的检查。在


Tags: 方法namestringdocvaluedefpassattrs
1条回答
网友
1楼 · 发布于 2024-04-20 13:22:44

它们是不可赎回的。classmethod和{}是{a1},它们不实现{}。HOWTO实际上给出了如何在纯python中实现它们的示例,因此,例如classmethod对象:

class ClassMethod(object):
    "Emulate PyClassMethod_Type() in Objects/funcobject.c"

    def __init__(self, f):
        self.f = f

    def __get__(self, obj, klass=None):
        if klass is None:
            klass = type(obj)
        def newfunc(*args):
            return self.f(klass, *args)
        return newfunc

注意,函数对象也是描述符。它们恰好是可调用的描述符。在

相关问题 更多 >