Reputation: 4298
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?
Upvotes: 5
Views: 23206
Reputation: 20291
Add self.initialize()
to myfunc()
, this should do what you are looking for.
class MyClass(object):
def __init__(self):
pass
def initialize(self):
print("I'm doing some initialization")
def myfunc(self):
self.initialize()
print("This is myfunc()!")
Try:
>>> a = MyClass()
>>> a.myfunc()
I'm doing some initialization
This is myfunc()!
Edit:
However, the practice is to use decorators
as suggested by DevShark.
It's discussed in another post, see Python decorators in classes
Upvotes: 3
Reputation: 96
You could make a wrapper function:
def wrapper(self, func_name):
self.initialize()
self.func_name()
def myfunc1(self):
# do something
def myfunc2(self):
# do something
obj.wrapper(myfunc1)
obj.wrapper(myfunc2)
Upvotes: 2
Reputation: 9112
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.
Upvotes: 4