According to the docs on inheritance:
Derived classes may override methods of their base classes. Because methods have no special privileges when calling
Here's the example you requested. This prints chocolate
.
class Base:
def foo(self):
print("foo")
def bar(self):
self.foo()
class Derived(Base):
def foo(self):
print("chocolate")
d = Derived()
d.bar() # prints "chocolate"
The string chocolate
is printed instead of foo
because Derived
overrides the foo()
function. Even though bar()
is defined in Base
, it ends up calling the Derived
implementation of foo()
instead of the Base
implementation.