(beginners) howto ascribe _all_ fields of parent class to child class?

Steve Holden steve at holdenweb.com
Wed Mar 14 12:53:25 EDT 2007


dmitrey wrote:
> Hi all,
> I'm rewriting some code from other language  to Python; can anyone
> explain me which way is the simpliest:
> I have
> class C1():
>     def __init__(self):
>          self.a = 5
> 
> class C2(C1):
>     def __init__(self):
>          self.b = 8
> 
> c = C2()
> print c.b#prints 8
> print c.a#prints error, because field a is absent
> 
> so how can I wrote the code that I'll got all class C1 fields (not
> only funcs)
> 
> Thank you in advance,
> Dmitrey
> 

The only problem here is that your subclass doesn't call the __init__ 
method of the superclass. Rewrite your C2 definition to read

class C2(C1):
     def __init__(self):
          C1.__init__(self)
          self.b = 8

and you should find your example works as you want.

regards
  Steve
-- 
Steve Holden       +44 150 684 7255  +1 800 494 3119
Holden Web LLC/Ltd          http://www.holdenweb.com
Skype: holdenweb     http://del.icio.us/steve.holden
Blog of Note:          http://holdenweb.blogspot.com
See you at PyCon?         http://us.pycon.org/TX2007




More information about the Python-list mailing list