In <[EMAIL PROTECTED]>, tmp123 wrote: > The following small program gives an error: > > #!/usr/bin/python > # > > class A: > def __init__(self): > self.v1=1 > > def __repr__(self): > return "v1=%d\n" % self.v1 > > class B(A): > def __init__(self,a): > self=a > self.v2=2 > > def __repr__(self): > return A.__repr__(self) + ("v2=%d\n" % self.v2) > > x=A() > print x > > y=B(x) > print y > > > > $ ./prueba.pl > v1=1 > > Traceback (most recent call last): > File "./prueba.pl", line 23, in <module> > print y > File "./prueba.pl", line 17, in __repr__ > return A.__repr__(self) + ("v2=%d\n" % self.v2) > File "./prueba.pl", line 9, in __repr__ > return "v1=%d\n" % self.v1 > AttributeError: B instance has no attribute 'v1' > > > It seems that the statement "self=a" is not the correct way to copy > all the fields of the base class from the __init__ argument to the new > object.
This binds the local name `self` to the same object that is bound to `a`. Now you have lost the reference to the instance, so the next line sets the attribute `v2` on the object passed to the constructor of the `B` object. > Of course, it is not an option to copy one by one all the fields of > class A inside the __init__ of B. > > Several variants of the program produces similar results. > > Please, could someone explain which way is the correct way? Call the `__init__()` of `A`: class B(A): def __init__(self, a): A.__init__(self) self.v2 = 2 Ciao, Marc 'BlackJack' Rintsch -- http://mail.python.org/mailman/listinfo/python-list