python中的静态方法和类方法不可调用吗? [英] Are staticmethod and classmethod in python not callable?

查看:51
本文介绍了python中的静态方法和类方法不可调用吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在编写一个元类来强制类和实例方法的文档字符串.令我惊讶的是 staticmethod 和 classmethod 不像实例方法那样 callable .我不知道为什么?

I was writing a metaclass to force docstring for class and instance method. Well to my surprise staticmethod and classmethod are not callable just like instance method. I am not sure why?

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

我无法理解为什么它们不可调用?如果我不为他们定义文档字符串,他们似乎会通过我的检查.

I am not able to understand why are they not callable? They seems to pass my check if I don't define docstring for them.

推荐答案

它们不可调用.classmethodstaticmethod描述符对象,并且它们不实现__call__.HOWTO 实际上提供了如何实施的示例它们在纯 python 中,例如 classmethod 对象:

They are not callable. classmethod and staticmethod are descriptor objects, and they do not implement __call__. The HOWTO actually gives examples of how you might implement them in pure python, so for example classmethod objects:

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

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

Note, function objects are descriptors too. They just happen to be callable descriptors.

这篇关于python中的静态方法和类方法不可调用吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆