having a function called after the constructor/__init__ is done

Steven D'Aprano steven at REMOVE.THIS.cybersource.com.au
Tue Mar 17 04:55:01 CET 2009

On Mon, 16 Mar 2009 20:11:18 -0700, thomas.hansen at gmail.com wrote:

> Hi all,
> We've been breaking our heads over a good way of accomplishing an
> "on_load" event in our multitouch GUI frameowork PyMT.  We think we'd
> like to trigger an "on_load" event after a class is fully instantiated
> Can I do something fancy with metaclasses here?

class MetaLoad(type):
    def __new__(cls, name, bases, dict):
        obj = type.__new__(cls, name, bases, dict)
        return obj
    def __call__(cls, *args, **kwargs):
        instance = super(MetaLoad, cls).__call__(*args, **kwargs)
        return instance

class Parrot(object):
    __metaclass__ = MetaLoad
    def __init__(self, colour='blue'):
        print "I'm a Norwegian %s." % colour
    def on_load(self):
        print "Loaded"


More information about the Python-list mailing list