在Python中,给定实例从中继承特定方法的类

时间:2014-03-06 08:25:43

标签: python inheritance introspection

我知道在Python中,给定一个类ClassA,带有

inspect.getmembers(ClassA, predicate=inspect.ismethod)

我可以迭代ClassA中存在的不同方法。还收集了继承的方法,这在我的案例中很方便。但是,根据method1的特定方法ClassA,我需要的是获取ClassA继承method1的类。可能是ClassA本身,或其任何父母/祖父母。我以为我可以递归遍历__bases__属性,在每一步查找method1属性。但也许这个功能已经在某个地方实现了。还有另一种方式吗?

1 个答案:

答案 0 :(得分:4)

使用inspect.getmro()查看MRO(方法解析顺序)(适用于旧式和新式类):

def class_for_method(cls, method):
    return next((c for c in inspect.getmro(cls) 
                 if method.__func__ in vars(c).values()), None)

目前没有stdlib方法来搜索你,没有。

演示:

>>> import inspect
>>> def class_for_method(cls, method):
...     return next((c for c in inspect.getmro(cls) 
...                  if method.__func__ in vars(c).values()), None)
... 
>>> class Base1(object):
...     def foo(self): pass
... 
>>> class Base2(object):
...     pass
... 
>>> class ClassA(Base1, Base2):
...     pass
... 
>>> class_for_method(ClassA, ClassA.foo)
<class '__main__.Base1'>

如果未找到基类,则上述表达式返回None

>>> class Bar:
...     def spam(): pass
... 
>>> class_for_method(ClassA, Bar.spam) is None
True