decorating a method in multiple child classes

Duncan Booth duncan.booth at invalid.invalid
Thu Jul 17 16:58:44 EDT 2008


1x7y2z9 at gmail.com wrote:

> I wish to decorate all of the CX.func() in the same way.  One way to
> do this is to add a decorator to each of the derived classes.  But
> this is tedious and involves modifying multiple files.
> 
> Is there a way to modify the parent class and have the same effect?
> Or some other way neater than the above?
> 

Use a metaclass.

>>> def decorate(f):
	print "decorating", f
	return f

>>> class meta(type):
	def __init__(self, name, bases, dictionary):
		if 'func' in dictionary:
			dictionary['func'] = decorate(dictionary['func'])
		type.__init__(self, name, bases, dictionary)

		
>>> class P(object):
	__metaclass__ = meta

	
>>> class C1(P):
	def func(self): pass

	
decorating <function func at 0x0119B370>
>>> 



More information about the Python-list mailing list