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?
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.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
argsandkwargs