another question on metaclasses
Greg Chapman
glc at well.com
Wed Dec 11 08:36:03 EST 2002
On 10 Dec 2002 11:01:17 -0800, mis6 at pitt.edu (Michele Simionato) wrote:
>i.e. what I want. Nevertheless, I wonder if there are cases where this script
>could break down, then I ask the Python gurus for comments and feedback.
It may break if any of the Autoinit classes do not have an __init__ method:
class B(Autoinit):
def __init__(self,*args,**kw):
print "This is B.__init__"
class C(B):
pass
class D(C):
def __init__(self,*args,**kw):
print "This is D.__init__"
d=D()
prints:
This is B.__init__
This is B.__init__
This is D.__init__
This is because cls.__init__ will return the nearest base class's __init__ if
cls does not itself define __init__. Your meta __init__ should probably look
like:
def __init__(cls,name,bases,dict):
child_init=cls.__dict__.get('__init__')
def double_init(self,*args,**kw):
"Both the super and the child __init__ are called"
super(cls,self).__init__(self,*args,**kw)
if child_init:
child_init(self,*args,**kw)
setattr(cls,'__init__',double_init)
---
Greg Chapman
More information about the Python-list
mailing list