less obvious "super"

Nagarajan naga86 at gmail.com
Mon Sep 10 07:46:02 EDT 2007


On Sep 10, 4:20 pm, Duncan Booth <duncan.bo... at invalid.invalid> wrote:
> Nagarajan <nag... at gmail.com> wrote:
> > Here is what I need to achieve..
>
> > class A :
> >     def __init__( self ):
> >         self.x  = 0
>
> Don't use old style classes. If you are planning to use 'super' then you
> must use new-style classes, so use 'object' as a base class here.
>
>
>
> > class B ( A ):
> >     def __init__( self, something ):
> >         # Use "super" construct here so that I can "inherit" x of A
> >         self.y  = something
>
> > How should I use "super" so that I could access the variable "x" of A
> > in B?
>
> If you aren't worried about diamond shaped multiple inheritance
> hierarchies then just use:
>
> class B ( A ):
>     def __init__( self, something ):
>         A.__init__(self)
>         self.y  = something
>
> If you are then:
>
> class B ( A ):
>     def __init__( self, something ):
>         super(B, self).__init__()
>         self.y  = something
>
> When you use super you usually just want the current class and current
> instance as parameters. Putting that together:
>
> >>> class A(object):
>
>     def __init__( self ):
>         self.x  = 0
>
> >>> class B ( A ):
>
>     def __init__( self, something ):
>         super(B, self).__init__()
>         self.y  = something
>
>
>
> >>> obj = B(3)
> >>> obj.x
> 0
> >>> obj.y
> 3


What's the difference b/w:
     class A:
and
     class A ( object ):

Thanks.




More information about the Python-list mailing list