July 2002
Intermediate to advanced
608 pages
15h 46m
English
Credit: Ken Seehof
You need to add functionality to an existing class without changing the source code for that class, and inheritance is not applicable (since it would make a new class, not change the old one).
Again, this is a case for introspection and dynamic change. The
enhance_method
function alters a klass class object to substitute
a named method with an enhanced version, decorated by the
replacement
function argument. The
method_logger
method exemplifies a typical case of replacement
by decorating any method with print statements
tracing its calls and returns:
# requires Python 2.1, or 2.2 with classic classes only from _ _future_ _ import nested_scopes import new def enhance_method(klass, method_name, replacement): 'replace a method with an enhanced version' method = getattr(klass, method_name) def enhanced(*args, **kwds): return replacement(method, *args, **kwds) setattr(klass, method_name, new.instancemethod(enhanced, None, klass)) def method_logger(old_method, self, *args, **kwds): 'example of enhancement: log all calls to a method' print '*** calling: %s%s, kwds=%s' % (old_method._ _name_ _, args, kwds) return_value = old_method(self, *args, **kwds) # call the original method print '*** %s returns: %r' % (old_method._ _name_ _, return_value) return return_value def demo( ): class Deli: def order_cheese(self, cheese_type): print 'Sorry, we are completely out of %s' % cheese_type d = Deli( ) d.order_cheese('Gouda') enhance_method(Deli, ...Read now
Unlock full access