I was reading the Python docs about classes and came across this paragraph which I'm not sure about:
Derived classes may override methods of their base classes. Because methods have no special privileges when calling other methods of the same object, a method of a base class that calls another method defined in the same base class may end up calling a method of a derived class that overrides it. (For C++ programmers: all methods in Python are effectively virtual.)
Example:
class A:
def foo(self):
self.bar()
def bar(self):
print "from A"
class B(A):
def foo(self):
self.bar()
def bar(self):
print "from B"
Does this mean that an object of class A obj = A()
can somehow end up printing "from B"? Am I reading this correctly? I apologize if this doesn't make sense. I'm a bit confused as to how python handles Inheritance and overriding. Thanks!
Access Overridden Function in C++ To access the overridden function of the base class, we use the scope resolution operator :: . We can also access the overridden function by using a pointer of the base class to point to an object of the derived class and then calling the function from that pointer.
Even though the derived class can't call it in the base class, the base class can call it which effectively calls down to the (appropriate) derived class. And that's what the Template Method pattern is all about.
But, since you have overridden the parent method how can you still call it? You can use super. method() to force the parent's method to be called.
Now we will create a Derived class that will extend this Base class i.e. In this class we will override the display() function i.e. Now if we create a Derived class object and call this overridden display() function from it , then due to dynamic binding in Java, always derived class display() method will be called i.e.
No. There's no way the superclass can know anything about the subclass. What it means is if you instantiate the subclass B, and it inherits a method foo()
, and overrides a method bar()
, then when you call foo()
, that will call the bar()
definition in B, not the bar()
definition in A. This is not what the superclass writer intended - he expected his call to bar()
to go to his own definition.
My answer doesn't necessarily contradict the ones posted already, but it does show a way to get the base class to print "from B" by calling the base class method from the inherited class. The base class still calls the inherited class method as it is working from the inherited self. Perhaps this is the type of situation the paragraph is referring to?
class A:
def foo(self):
self.bar()
def bar(self):
print("from A")
class B(A):
def foo(self):
super().foo()
def bar(self):
print("from B")
A().foo() #prints "from A"
B().foo() #prints "from B" but indirectly through the base class
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With