我正在编写一个元类来强制类和实例方法使用文档字符串。令我惊讶的是 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
我无法理解为什么它们不可调用?如果我不为他们定义文档字符串,他们似乎会通过我的检查。
它们不可调用。classmethod
and staticmethod
are 描述符对象,并且他们没有实施__call__
. The 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
Note, 函数对象也是描述符。它们恰好是可调用描述符。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)