469,332 Members | 6,650 Online
Bytes | Developer Community
New Post

Home Posts Topics Members FAQ

Post your question to a community of 469,332 developers. It's quick & easy.

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

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

Mar 14 '07 #1
2 1298
dmitrey schrieb:
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
Mar 14 '07 #2
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

Mar 14 '07 #3

This discussion thread is closed

Replies have been disabled for this discussion.

Similar topics

16 posts views Thread by Suzanne Vogel | last post: by
6 posts views Thread by jalkadir | last post: by
4 posts views Thread by Danny Tuppeny | last post: by
3 posts views Thread by Eddie | last post: by
9 posts views Thread by susan.f.barrett | last post: by
10 posts views Thread by Goran Djuranovic | last post: by
1 post views Thread by CARIGAR | last post: by
reply views Thread by zhoujie | last post: by
1 post views Thread by haryvincent176 | last post: by
reply views Thread by Marylou17 | last post: by
1 post views Thread by Marylou17 | last post: by
By using this site, you agree to our Privacy Policy and Terms of Use.