Another way is to design your classes such that you extend only a part of the function.
So for example, we have an object where we must called object.execute() which involves printing some generic message, some processing, followed by another generic message.
And depending on the current state of the program, different processing is required.
we could do something like
PHP Code:
class defaultExecutor(object):
def execute(self, *args, **kwargs):
print "hello there"
self.process(*args, **kwargs)
print "done stuff"
def process(self, *args, **kwargs):
"""this becomes the method to be overridden"""
x = 1
x += 1
print x
class OtherExecutor(defaultExecutor):
def process(self, *args, **kwargs):
return 3
To make life nice you'd design it so that process has some specific set of arguements instead of using * and ** magic (unless of course that would be appropiate)
I tend to do this when I have classes that all need to do the same thing in __init__ but still might require something different in each case, so I don't have to overwrite __init__ and do super calls and such.
Also, another way is to use function decorators.
for example
PHP Code:
def decorator(func):
def wrapped(*args, **kwargs):
print "hello there"
func(*args, **kwargs)
print "done stuff"
return wrapped
class otherExecutor(object):
@decorator
def execute(self, *args, **kwargs):
return 3
Bookmarks