Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calling an overridden method, superclass an calls overridden method

This code throws an exception, AttributeError, "wtf!", because A.foo() is calling B.foo1(), shouldn't it call A.foo1()? How can I force it to call A.foo1() (and any method call inside A.foo() should call A.*)

class A(object):
    def foo(self):
        print self.foo1()

    def foo1(self):
        return "foo"

class B(A):
    def foo1(self):
        raise AttributeError, "wtf!"

    def foo(self):
        raise AttributeError, "wtf!"

    def foo2(self):
        super(B, self).foo()

myB = B()
myB.foo2()
like image 959
Perico de los palotes Avatar asked Oct 22 '11 12:10

Perico de los palotes


People also ask

Can you invoke an overridden superclass method from a subclass?

Instance MethodsThe ability of a subclass to override a method allows a class to inherit from a superclass whose behavior is "close enough" and then to modify behavior as needed. The overriding method has the same name, number and type of parameters, and return type as the method that it overrides.

How do you call a superclass method?

To explicitly call the superclass constructor from the subclass constructor, we use super() . It's a special form of the super keyword. super() can be used only inside the subclass constructor and must be the first statement.


2 Answers

In class A instead of calling self methods you need to call A methods and pass in self manually.

This is not the normal way of doing things -- you should have a really good reason for doing it like this.

class A(object):
    def foo(self):
        print A.foo1(self)

    def foo1(self):
        return "foo"

class B(A):
    def foo1(self):
        raise AttributeError, "wtf!"

    def foo(self):
        raise AttributeError, "wtf!"

    def foo2(self):
        super(B, self).foo()

myB = B()
myB.foo2()
like image 159
Ethan Furman Avatar answered Oct 26 '22 16:10

Ethan Furman


In the code:

def foo2(self):
    super(B, self).foo()

self is an instance of B.

When a method derived from A is called by an instance of B it will start looking in the namespace from B, and only if the method is not found (e.g. is not overridden by B) the implementation from A is used, but always with self referring to B. At no point self is an instance of A.

like image 28
extraneon Avatar answered Oct 26 '22 16:10

extraneon