Python动态添加到函数 [英] Python add to a function dynamically
本文介绍了Python动态添加到函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如何在之前或之后向现有功能添加代码?
how do i add code to an existing function, either before or after?
例如,我有一堂课:
class A(object):
def test(self):
print "here"
我该如何编辑带有元编程的类,这样我就可以做到
how do i edit the class wit metaprogramming so that i do this
class A(object):
def test(self):
print "here"
print "and here"
也许可以通过某种方式附加另一个功能进行测试?
maybe some way of appending another function to test?
添加另一个功能,例如
def test2(self):
print "and here"
并将原件更改为
class A(object):
def test(self):
print "here"
self.test2()
有没有办法做到这一点?
is there a way to do this?
推荐答案
如果需要,可以使用装饰器来修改函数.但是,由于它不是在函数初始定义时应用的修饰符,因此您将无法使用@
语法糖来应用它.
You can use a decorator to modify the function if you want. However, since it's not a decorator applied at the time of the initial definition of the function, you won't be able to use the @
syntactic sugar to apply it.
>>> class A(object):
... def test(self):
... print "orig"
...
>>> first_a = A()
>>> first_a.test()
orig
>>> def decorated_test(fn):
... def new_test(*args, **kwargs):
... fn(*args, **kwargs)
... print "new"
... return new_test
...
>>> A.test = decorated_test(A.test)
>>> new_a = A()
>>> new_a.test()
orig
new
>>> first_a.test()
orig
new
请注意,它也会修改现有实例的方法.
Do note that it will modify the method for existing instances as well.
编辑:使用args
和kwargs
这篇关于Python动态添加到函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文