This question already has an answer here:
Why are python static/class method not callable?
                                
                                    (1个答案)
                                
                        
                                9个月前关闭。
            
                    
我正在编写一个元类来强制将docstring用于类和实例方法。令我惊讶的是,staticmethod和classmethod不像实例方法那样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


我不明白为什么他们不能打电话?如果我没有为他们定义文档字符串,它们似乎通过了我的检查。

最佳答案

它们是不可调用的。 classmethodstaticmethoddescriptor objects,它们不实现__call__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


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

10-06 01:44