python-3.x - 在 Python 中查找方法的所有者类
问题描述
我正在编写装饰器,我需要做的部分工作是辨别函数是函数还是方法。有没有办法可以找到给定方法所属的类?
例如,如果我要运行这段代码,我可以写什么getOwner
来exampleFunc
打印类似的东西<class '__main__'.Example>
?
class Example:
def method(self):
print("I'm a method")
def exampleFunc(func):
owner = getOwner(func)
print(owner)
test = Example()
exampleFunc(test.method)
解决方案
如果您需要做的就是弄清楚表现得像函数的东西是方法或函数,那是types
模块的一个目的。
import types
def is_method(f):
return type(f) == types.MethodType
如果类函数对象是一个方法,您可以按如下方式找到它的父类。
更新为 Python3 兼容性打了补丁。
def method_parent(f):
return f.__self__