Dynamic method resolution on a super() object
我需要按名称在
我尝试使用
如何正确而优雅地做到这一点?
例如:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | class A(object): def p (self): skip class B(object): def p (self): skip class AB (A,B): def p (self): skip ab = AB() o = super(ab.__class__, ab) print dir(o) print o.__getattribute__("p").__code__ print o.p.__code__ |
此代码输出:
1 2 3 4 | ['__class__', '__delattr__', '__doc__', '__format__', '__get__', '__getattribute__', '__hash__', '__init__', '__new__', '__reduce__', '__reduce_ex__', '__repr__ ', '__self__', '__self_class__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__thisclass__'] <code object p at 000000000205f2b0, file"b.py", line 10> # AB.p <code object p at 0000000000361cb0, file"b.py", line 2> # A.p |
你要找的是
1 2 | >>> getattr(o,"p") <bound method A.p of <__main__.AB object at 0x0000000000AA8160>> |
直接使用