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?
While defining a function in Python, you can pass argument(s) into the function by putting them inside the parenthesis. In the example above: I passed 2 arguments into the function named addNum. I told it to print the sum of the 2 arguments to the terminal.
Python Code can be dynamically imported and classes can be dynamically created at run-time. Classes can be dynamically created using the type() function in Python. The type() function is used to return the type of the object. The above syntax returns the type of object.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With