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!
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 methodbar(), then when you callfoo(), that will call thebar()definition in B, not thebar()definition in A. This is not what the superclass writer intended – he expected his call tobar()to go to his own definition.