如何获取 parent 类 python 的函数

how to get functions of parent classes python

如何获得 parent class 的功能(相对于未绑定的方法)?在下面的示例中,我想获取 parent class 的函数和文档字符串。我们有一个方法列表 (post, get),在 parent 或 child class 中应该有一个匹配的函数名称。我们需要获取函数 object 并查看其属性。对于 child class,这很简单,但我不知道如何为 parent class.

我简化了下面的示例,但在我们更复杂的情况下,我们有一个大型烧瓶应用程序,我们重写了它以使用一组通用的 base/parent classes(带有修饰函数). Our third party library uses __dict__.get to generate swagger documentation.

class A():

    def get(self):
        """geta"""
        desc = 'geta'
        print('got it')


class B(A):

    def post(self):
        """postb"""
        desc = 'postb'
        print('posted')


# this is the part we need to change:
methods = ['post', 'get']
for method in methods:
    f = B.__dict__.get(method, None)
    print(f)
    print(f.__doc__)

结果将是:

<function post at 0x1054f96e0>
postb
None
None

我想迭代 B.bases 寻找匹配的方法名称。我担心一组又长又深的嵌套 if 和 for 循环,并希望有一个更 pythonic 和干净的解决方案。 dir(B) 列出了所有函数,但我不知道如何获取函数,除非通过 dict

你可以使用class__mro__魔术方法:

In [3]: class A:  #(object) if using 2.x
   ...:     def post(s):
   ...:         """foo"""
   ...:         pass
   ...:
   ...:

In [4]: class B(A):
   ...:     def get(s):
   ...:         """boo"""
   ...:         pass
   ...:

In [8]: methods = ['get', 'post']


In [10]: for m in methods:
    ...:     for c in B.__mro__:
    ...:         f = c.__dict__.get(m)
    ...:         if f:
    ...:             print(f)
    ...:             print(f.__doc__)
                     break # if you don't want duplicate functions
                           # (with subclass listed first)
    ...:
<function B.get at 0x102ece378>
boo
<function A.post at 0x102ee8730>
foo

但是,如果您的其中一个子class正在覆盖其父项的方法(不确定您是否关心或它是否是您想要的),这可能会打印该函数两次