小编典典

获取定义方法的类

python

如何获得在Python中定义方法的类?

我想要以下示例打印“ __main__.FooClass”:

class FooClass:
    def foo_method(self):
        print "foo"

class BarClass(FooClass):
    pass

bar = BarClass()
print get_class_that_defined_method(bar.foo_method)

阅读 209

收藏
2021-01-20

共1个答案

小编典典

import inspect

def get_class_that_defined_method(meth):
    for cls in inspect.getmro(meth.im_class):
        if meth.__name__ in cls.__dict__: 
            return cls
    return None
2021-01-20