好吧,如果你真的想要,你可以使用这样的东西,虽然我认为它有点 hackish:
class Example(object):
def method1(self):
print 1
def method2(self):
print 2
def __getattribute__(self, name):
def f():
# todo: check if it's actually a function or not before calling
r = object.__getattribute__(self, name)()
print 'hello world'
return r
return f
但我同意那些已经对你的问题发表评论的人:你在这里试图解决一个实际的问题吗?
另外,我认为这隐藏了每个方法的末尾都会发生一些事情的事实,并且可能会掩盖代码。请记住:显式优于隐式。
当然,您可以将其放入类装饰器中:
def SaysHelloAfterEveryMethod(klass):
def __getattribute__(self, name):
def f():
# todo: check if it's actually a function or not
r = object.__getattribute__(self, name)()
print 'hello world'
return r
return f
klass.__getattribute__ = __getattribute__
return klass
@SaysHelloAfterEveryMethod
class Example(object):
def method1(self):
print 1
def method2(self):
print 2