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

D

dmitrey

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
 
D

Diez B. Roggisch

dmitrey said:
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)

You need to call the super classes __init__-method. There are several
ways to do so, in your case

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

should do the trick.

DIEZ
 
S

Steve Holden

dmitrey said:
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
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,992
Messages
2,570,220
Members
46,805
Latest member
ClydeHeld1

Latest Threads

Top