views:

53

answers:

1

Newbie Python question. I have a class that inherits from several classes, and some of the specialization classes override some methods from the base class. In certain cases, I want to call the unspecialized method. Is this possible? If so, what's the syntax?

class Base(object):
    def Foo(self):
        print "Base.Foo"

    def Bar(self):
        self.Foo()  # Can I force this to call Base.Foo even if Foo has an override?


class Mixin(object):
    def Foo(self):
        print "Mixin.Foo"


class Composite(Mixin, Base):
    pass


x = Composite()
x.Foo()  # executes Mixin.Foo, perfect
x.Bar()  # indirectly executes Mixin.Foo, but I want Base.Foo
+5  A: 

you can specifically make the call you want using the syntax

Base.Foo(self)

in your case:

class Base(object):
    # snipped

    def Bar(self):
        Base.Foo(self)  # this will now call Base.Foo regardless of if a subclass
                        # overrides it

# snipped


x = Composite()
x.Foo()  # executes Mixin.Foo, perfect
x.Bar()  # prints "Base.Foo"

This works because Python executes calls to bound methods of the form

instance.method(argument)

as if they were a call to an unbound method

Class.method(instance, argument)

so making the call in that form gives you the desired result. Inside the methods, self is just the instance that the method was called on, i.e, the implicit first argument (that's explicit as a parameter)

Note however that if a subclass overrides Bar, then there's nothing (good) that you can effectively do about it AFAIK. But that's just the way things work in python.

aaronasterling
Thanks! I think I knew all that, but I overcomplicated it in my head.
Adrian McCarthy