如何获取父类的功能(与未绑定的方法相反)?在下面的示例中,我想获取父类的函数和doc字符串。我们有一个方法列表(post,get),在父类或子类中应该有一个匹配的函数名。我们需要获取函数对象并查看其属性。对于子类,这很容易,但我不知道如何为父类做。
我已经简化了下面的示例,但在我们更复杂的情况下,我们有一个大型烧瓶应用程序,我们重写为使用一组通用的基类/父类(带有修饰函数)。 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. base 寻找匹配的方法名称。我担心嵌套if和for循环的长而深的一组,并希望有一个更加pythonic和干净的解决方案。 dir(B)
列出了所有函数,但我不知道如何通过dict
获取函数。
答案 0 :(得分:2)
您可以使用类__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
但是,如果您的某个子类从其父级覆盖某个方法(不确定您是否关心或者您想要它),这可能会打印该函数两次