newbie: copy base class fields

tmp123 tmp123 at menta.net
Thu May 3 10:14:04 EDT 2007


Hello,

Thanks for your time.

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.

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?

Thanks a lot.




More information about the Python-list mailing list