python中的staticmethod和classmethod是不可调用的? [重复]

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

这个问题在这里已有答案:

我正在编写一个元类来强制类和实例方法的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

我无法理解他们为什么不可赎回?如果我没有为他们定义文档字符串,他们似乎通过我的检查。

python python-3.x metaclass
1个回答
2
投票

他们不可赎回。 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

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

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