在 Python 中,假设我有一个如下所示的基本类结构:
class Foo(object):
def do_something(self):
print 'doing a thing'
def do_another_thing(self):
print 'doing another thing'
class Bar(Foo):
def do_another_thing(self):
super(bar, self).do_another_thing()
print 'doing more stuff still'
我了解该__mro__
属性的构造方式,但我想添加日志记录,以便在输出中查看每个类调用时它找到/调用的方法。因此,例如,我希望它记录如下评论:
f = Foo()
b = Bar()
f.do_something()
#print 'Implementing foo method do_something'
b.do_something()
#print 'Did not find method do_something for bar'
#print 'Implementing foo method do_something'
f.do_another_thing()
#print 'Implementing foo method do_another_thing'
b.do_another_thing()
#print 'Implementing bar method do_another_thing'
#print 'Implementing foo method do_another_thing'
我一直在摆弄__getattribute__
and __get__
,但显然我对这些方法的理解还不够好,无法按需要实现。我还研究了使用装饰器,但我认为以某种方式使用描述符可能是此处采用的路线。
这是我到目前为止所尝试的:
class Bar(Foo):
def do_another_thing(self):
super(Bar, self).do_another_thing()
print 'doing more stuff still'
def __getattribute__(self, key):
self_dict = object.__getattribute__(type(self), '__dict__')
if key in self_dict:
print 'Implementing {} method {}'.format(type(self).__name__, key)
v = object.__getattribute__(self, key)
if hasattr(v, '__get__'):
return v.__get__(None, self)
return v
print 'Did not find method {} for {}'.format(key, type(self).__name__)
mro = object.__getattribute__(type(self), '__mro__')
for thing in mro[1:]:
v = thing.__getattribute__(self, key)
if hasattr(v, '__get__'):
return v.__get__(None, self)
return v
我也在__getattribute__
Foo 中重新定义了这个,我的输出如下:
Implementing Foo method do_something
doing a thing
Did not find method do_something for Bar
Did not find method do_something for Bar
doing a thing
Implementing Foo method do_another_thing
doing another thing
Implementing Bar method do_another_thing
doing another thing
doing more stuff still
因此,我能够在第一级继承捕获正确的日志记录,但无法正确地将调用从 Bar 传递回 Foo,以便我可以利用 Foo 的__getattribute__
.