Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
416 views
in Technique[技术] by (71.8m points)

metaprogramming - Python add to a function dynamically

how do i add code to an existing function, either before or after?

for example, i have a class:

 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?

add another function such as

 def test2(self):
      print "and here"

and change the original to

 class A(object):
     def test(self):
         print "here"
         self.test2()

is there a way to do this?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.

EDIT: modified the args list for the decorator to the better version using args and kwargs


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...