如何推断到一个@staticmethod所属的类?
-
09-09-2019 - |
题
我试图实现infer_class
功能,给定的方法,计算出到该方法所属的类。
到目前为止,我有这样的事情:
import inspect
def infer_class(f):
if inspect.ismethod(f):
return f.im_self if f.im_class == type else f.im_class
# elif ... what about staticmethod-s?
else:
raise TypeError("Can't infer the class of %r" % f)
它不为@静态方法-S工作,因为我无法想出一个办法来实现这一目标。
任何建议?
这里的infer_class
在动作:
>>> class Wolf(object):
... @classmethod
... def huff(cls, a, b, c):
... pass
... def snarl(self):
... pass
... @staticmethod
... def puff(k,l, m):
... pass
...
>>> print infer_class(Wolf.huff)
<class '__main__.Wolf'>
>>> print infer_class(Wolf().huff)
<class '__main__.Wolf'>
>>> print infer_class(Wolf.snarl)
<class '__main__.Wolf'>
>>> print infer_class(Wolf().snarl)
<class '__main__.Wolf'>
>>> print infer_class(Wolf.puff)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 6, in infer_class
TypeError: Can't infer the class of <function puff at ...>
解决方案
这是因为staticmethods真的没有方法。由于是静态方法描述符返回原来的功能。有没有办法让通过该功能被访问的类。但没有真正的理由使用方法staticmethods无论如何,总是用classmethods。
,我发现对于staticmethods的唯一用途是函数对象存储为类属性而不是让他们变成方法。
其他提示
我有麻烦把自己真正的建议的这一点,但它似乎对简单的情况下工作,至少:
import inspect
def crack_staticmethod(sm):
"""
Returns (class, attribute name) for `sm` if `sm` is a
@staticmethod.
"""
mod = inspect.getmodule(sm)
for classname in dir(mod):
cls = getattr(mod, classname, None)
if cls is not None:
try:
ca = inspect.classify_class_attrs(cls)
for attribute in ca:
o = attribute.object
if isinstance(o, staticmethod) and getattr(cls, sm.__name__) == sm:
return (cls, sm.__name__)
except AttributeError:
pass
不隶属于 StackOverflow