Python: how to distinguish between inherited methods

New Python question. I have a class that inherits from several classes, and some specialization classes override some methods from the base class. In some cases, I want to name a non-specialized method. Is it possible? If so, what is 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 
+4
source share
1 answer

you can specifically make the required call 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 makes calls to related form methods.

 instance.method(argument) 

as if they were a call to an unrelated method

 Class.method(instance, argument) 

therefore, a call in this form gives the desired result. Inside methods, self is just an instance of a method call, i.e. Implicit first argument (explicit as parameter)

Note that if a subclass cancels Bar , then there is nothing (good) that you can effectively do AFAIK with it. But this is how everything works on python.

+6
source

All Articles