multiple inheritance

Andreas Kostyrka andreas at kostyrka.org
Thu Jun 9 04:19:10 EDT 2005


I'm sure it's documented somewhere, but here we go :)

The correct usage is super(MyClass, self)

The idea is that super allows for cooperative calls. It uses MyClass to locate
what class "above" to call. 

This way you can something like that:

class A(object):
    def bar(self):
        print "A"
        #getattr(super(A, self),"bar", lambda : None)()

class B(object):
    def bar(self):
        print "B"
        #getattr(super(B, self),"bar", lambda : None)()

class C(A,B):
    def bar(self):
        print "C"
        getattr(super(C, self),"bar", lambda : None)()

print "-" * 20, "no super in A/B"
C().bar()

class A(object):
    def bar(self):
        print "A"
        getattr(super(A, self),"bar", lambda : None)()

class B(object):
    def bar(self):
        print "B"
        getattr(super(B, self),"bar", lambda : None)()

class C(A,B):
    def bar(self):
        print "C"
        getattr(super(C, self),"bar", lambda : None)()

print "-" * 20, "protected getattr/super in A/B"

C().bar()

class base(object):
    def bar(self):
        print "base"

class A(base):
    def bar(self):
        print "A"
        getattr(super(A, self), "bar", lambda : None)()

class B(base):
    def bar(self):
        print "B"
        getattr(super(B, self), "bar", lambda : None)()

class C(A,B):
    def bar(self):
        print "C"
        getattr(super(C, self), "bar", lambda : None)()

print "-" * 20, "base class without super call"
C().bar()

This produces:
-------------------- no super in A/B
C
A
-------------------- protected getattr/super in A/B
C
A
B
-------------------- base class without super call
C
A
B
base

Andreas
On Thu, Jun 09, 2005 at 12:56:53AM -0700, newseater wrote:
> i don't know how to call methods of super classes when using multiple
> inheritance. I've looked on the net but with no result :(
> 
> class a(object):
>     def foo(self):
>         print "a"
> 
> class b(object):
>     def foo(self):
>         print "a"
> 
> class c(a,b)
>     def foo(self):
>         super( ???? a).foo()
>         super( ???? b).foo()
> 
> r = c()
> r.foo()
> 
> -- 
> http://mail.python.org/mailman/listinfo/python-list



More information about the Python-list mailing list