Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do overridden method calls from base-class methods work?

Tags:

According to the docs on inheritance:

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.

How does that happen? Can someone illustrate this concept with a simple example?

like image 290
wow yoo Avatar asked Dec 20 '16 06:12

wow yoo


People also ask

How can we access the overridden method of base class from the derived class?

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.

Can you call an overridden method?

Invoking overridden method from sub-class : We can call parent class method in overriding method using super keyword. Overriding and constructor : We can not override constructor as parent and child class can never have constructor with same name(Constructor name must always be same as Class name).

Why you do override a method of a base class?

The main advantage of method overriding is that the class can give its own specific implementation to a inherited method without even modifying the parent class code.


1 Answers

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.

like image 116
IanPudney Avatar answered Oct 05 '22 09:10

IanPudney