【发布时间】:2010-10-31 06:13:49
【问题描述】:
我正在尝试实现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)
它不适用于@staticmethod-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 ...>
【问题讨论】:
-
你有源码,你可以阅读父类。你为什么需要这个?你想完成什么?
-
假设我想编写一个临时存根函数或方法的函数(以拦截调用或其他任何东西,用于测试目的)。为了能够做到这一点,我需要两个要素:包含函数的对象和函数名称,这样我就可以做到
setattr(obj, func_name, my_stub)。如果 f 是模块级函数,我使用inspect.getmodule(f)获取对象,使用f.__name__获取其名称。对于类方法和实例方法,我使用上面的代码。对于静态方法,我似乎不走运。
标签: python decorator static-methods inspect