向函数添加功能的典型方法是使用decorator(使用the wraps function):
from functools import wraps
def add_message(func):
@wraps
def with_additional_message(*args, **kwargs)
try:
return func(*args, **kwargs)
finally:
print "and here"
return with_additional_message
class A:
@add_message
def test(self):
print "here"
当然,这实际上取决于您要完成的工作。我经常使用装饰器,但如果我只想打印额外的消息,我可能会做类似的事情
class A:
def __init__(self):
self.messages = ["here"]
def test(self):
for message in self.messages:
print message
a = A()
a.test() # prints "here"
a.messages.append("and here")
a.test() # prints "here" then "and here"
这不需要元编程,但是您的示例可能与您实际需要做的相比大大简化了。也许如果您发布有关您的特定需求的更多详细信息,我们可以更好地建议 Pythonic 方法是什么。
编辑:由于您似乎想要调用函数,因此您可以拥有函数列表而不是消息列表。例如:
class A:
def __init__(self):
self.funcs = []
def test(self):
print "here"
for func in self.funcs:
func()
def test2():
print "and here"
a = A()
a.funcs.append(test2)
a.test() # prints "here" then "and here"
请注意,如果您想添加将被A 的所有实例调用的函数,那么您应该将funcs 设为类字段而不是实例字段,例如
class A:
funcs = []
def test(self):
print "here"
for func in self.funcs:
func()
def test2():
print "and here"
A.funcs.append(test2)
a = A()
a.test() # print "here" then "and here"