Possibly a stupid question regarding Python Classes

Alan Kennedy alanmk at hotmail.com
Sun Nov 17 11:37:30 EST 2002


Adonis wrote:
> 
> Is this even possible:
> 
> class Foo:
>     def Bar(self):
>         print 'Foo'
> 
> class Fib(Foo):
>     def Bar(self):
>         # do the original Foo.Bar()
>         # NOTE: w/o needing to instantiate Foo
>         # then do:
>         print 'Bar'
> 

Adonis,

I think you want something like this.

class Fib(Foo):
    def Bar(self):
        # First call the superclass Bar() method
        Foo.Bar(self)
        print 'Bar'

>>> f = Fib()
>>> f.Bar()
Foo
Bar
>>>

If you don't want to hardcode the name of the superclass into your
method definition, you could also write it as follows:

class Fib(Foo):
    def Bar(self):
        self.__class__.__bases__[0].Bar(self)
        print 'Bar'

>>> f = Fib()
>>> f.Bar()
Foo
Bar
>>>

This works fine for single inheritance, but gets more complex when
multiple inheritance is introduced.

Also, I don't know if this approach is still recommended after the
introduction of New Style Classes in python 2.2.

regards,

-- 
alan kennedy
-----------------------------------------------------
check http headers here: http://xhaus.com/headers
email alan:              http://xhaus.com/mailto/alan



More information about the Python-list mailing list