Is there a way to force an instance method in Python to call another method prior to executing?
A simple example for demonstration:
class MyClass(object):
def __init__(self):
pass
def initialize(self):
print "I'm doing some initialization"
def myfunc(self):
print "This is myfunc()!"
I'd like some way to have myfunc() automatically call initialize() prior to running. If I do:
obj = MyClass()
obj.myfunc()
I'd like to see the following as the output:
I'm doing some initialization
This is myfunc()!
Without having to explicitly call initialize() within myfunc().
The reason for this is if I have many instances of "myfunc", say myfunc1, myfunc2, myfunc3, that all need to call "initialize", I'd rather have them all call initialize once in the same place, as opposed to manually calling the method each time. Is this something meta classes could do?
You can use a decorator in Python. Make the decorator call the function you want before the one called. You will be able to use the decorator in all your desired functions. This is syntactic sugar.
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