Velocity Reviews

Velocity Reviews (http://www.velocityreviews.com/forums/index.php)
-   Python (http://www.velocityreviews.com/forums/f43-python.html)
-   -   (beginners) howto ascribe _all_ fields of parent class to child class? (http://www.velocityreviews.com/forums/t484264-beginners-howto-ascribe-_all_-fields-of-parent-class-to-child-class.html)

dmitrey 03-14-2007 04:28 PM

(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


Diez B. Roggisch 03-14-2007 04:48 PM

Re: (beginners) howto ascribe _all_ fields of parent class to childclass?
 
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

Steve Holden 03-14-2007 04:53 PM

Re: (beginners) howto ascribe _all_ fields of parent class to childclass?
 
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



All times are GMT. The time now is 02:06 AM.

Powered by vBulletin®. Copyright ©2000 - 2014, vBulletin Solutions, Inc.
SEO by vBSEO ©2010, Crawlability, Inc.