having a function called after the constructor/__init__ is done

Michael Spencer mahs at telcopartners.com
Tue Mar 17 00:02:13 EDT 2009


thomas.hansen at gmail.com wrote:
...
> 
> So any ideas on how to get a function called on an object just after
> __init__ is done executing?
> --
> http://mail.python.org/mailman/listinfo/python-list
> 

Yes, you *can* use metaclasses - you need to override the type.__call__ method, 
which is what normally calls __new__ then __init__:

  >>> class MetaOnLoad(type):
  ...     def __call__(cls, *args, **kw):
  ...         obj=type.__call__(cls, *args, **kw)
  ...         obj.on_load()
  ...         return obj
  ...
  >>> class A(object):
  ...     __metaclass__ = MetaOnLoad
  ...     def __init__(self):
  ...         print "__init__ A"
  ...     def on_load(self):
  ...         print "on_load"
  ...
  >>> class B(A):
  ...     def __init__(self):
  ...         super(B,self).__init__()
  ...         print "__init__ B"
  ...
  >>> b=B()
  __init__ A
  __init__ B
  on_load
  >>> class C(B):
  ...     def __init__(self):
  ...         super(C,self).__init__()
  ...         print "__init__ C"
  ...
  >>> c=C()
  __init__ A
  __init__ B
  __init__ C
  on_load
  >>> #Check that __new__ machinery is still available:
  >>> class D(C):
  ...     def __new__(cls,*args, **kw):
  ...         obj = object.__new__(cls, *args, **kw)
  ...         print "__new__ D"
  ...         return obj
  ...
  >>> d=D()
  __new__ D
  __init__ A
  __init__ B
  __init__ C
  on_load
  >>>

HTH
Michael




More information about the Python-list mailing list