I'm trying to use metaclasses to implement the following functionality:
class foo( object ):
def __init__( self ):
self.val = 'foo'
def bar( self ):
print 'hello world'
print self.val
f = foo()
f.bar() #prints 'hello world' followed by foo
def newbar( self ):
super( **?**, self).bar()
print 'another world!'
fooNew = type('fooNew', (foo,), {'bar':newbar})
n = fooNew()
n.bar() # should print everything in f.bar() followed by 'another world!'
I understand I can use monkey patching to implement my own function newbar. However there is a subtle difference, I want the new bar function to first run the base class bar function and only then run any additional functionality.
How can I do this? or how could I do this better?
typeis the standard built-in metaclass. If people say "using metaclasses", they usually refer to defining custom metaclasses. All you do here is to use a rather inconvenient way to dynamically create a class.