> Programming Languages > Python
Various Topics Home | Disclaimer | Report Adult Posts

Various Topics on Python



Python - "A question about inheritance" in Programming Languages


Old 05-08-2005   #1
..serl.. ..ail.c..
 
Default A question about inheritance

Hello I have a question about inheritance in Python. I'd like to do
something like this:

cl*** cl1:
def __init__(self):
self.a = 1

cl*** cl2(cl1):
def __init__(self):
self.b = 2

But in such a way that cl2 instances have atributes 'b' AND 'a'.
Obviously, this is not the way of doing it, because the __init__
definition in cl2 overrides cl1's __init__.

Is there a 'pythonic' way of achieving this?

Armando Serrano

 
Old 05-08-2005   #2
..serl.. ..ail.c..
 
Default Re: A question about inheritance

Thanks.

Jp Calderone wrote:
> On 8 May 2005 12:07:58 -0700, arserlom@gmail.com wrote:
> >Hello I have a question about inheritance in Python. I'd like to do
> >something like this:
> >
> > cl*** cl1:
> > def __init__(self):
> > self.a = 1
> >
> > cl*** cl2(cl1):
> > def __init__(self):
> > self.b = 2
> >
> >But in such a way that cl2 instances have atributes 'b' AND 'a'.
> >Obviously, this is not the way of doing it, because the __init__
> >definition in cl2 overrides cl1's __init__.
> >
> >Is there a 'pythonic' way of achieving this?

>
> cl*** cl2(cl1):
> def __init__(self):
> cl1.__init__(self)
> self.b = 2
>
> Jp


 
Old 05-09-2005   #3
..ev.. ..tha..
 
Default Re: A question about inheritance

arserlom@gmail.com wrote:
> Hello I have a question about inheritance in Python. I'd like to do
> something like this:
>
> cl*** cl1:
> def __init__(self):
> self.a = 1
>
> cl*** cl2(cl1):
> def __init__(self):
> self.b = 2
>
> But in such a way that cl2 instances have atributes 'b' AND 'a'.
> Obviously, this is not the way of doing it, because the __init__
> definition in cl2 overrides cl1's __init__.
>
> Is there a 'pythonic' way of achieving this?


If there's a chance you might have multiple inheritance at some point in
this hierarchy, you might also try using super:

cl*** cl1(object): # note it's a new-style cl***
def __init__(self):
self.a = 1

cl*** cl2(cl1):
def __init__(self):
super(cl2, self).__init__()
self.b = 2

Note that you probably want a new-style cl*** even if you chose not to
use super in favor of Jp Calderone's suggestion. There are very few
cases for using old-style cl***es these days.

STeVe
 

Thread Tools
Display Modes





Powered by vBulletin®
Copyright ©2000 - 2009, Jelsoft Enterprises Ltd.
Search Engine Friendly URLs by vBSEO 3.3.0