Method Overriding in PythonAny object-oriented programming language can allow a subclass or child class to offer a customized implementation of a method already supplied by one of its superclasses or parent classes. This capability is known as method overriding. The term "override" refers to a method in a subclass that replaces a method in a superclass when both methods share the same name, parameters, signature, and return type (or sub-type). The object that calls a method will determine which version of the method is executed. When a method is called from an object of a parent class, the method's parent class version is executed; however, when a method is called from an object of a subclass, the child class version is executed. In other words, the version of an overridden method depends on the object being referenced, not the type of the reference variable. Example: Output: Inside Parent Inside Child Method Overriding with Multilevel and Multiple Inheritance1. Multiple Inheritance: A class is said to be a multiple inheritance when it is derived from more than one base class. Example: Let's look into the below implementation, where we want to override a method using only one parent class. Output: Inside Child Inside Parent2 2. Multilevel Inheritance: A Class is said to be multilevel inheritance if a child and grandchild relationship exists. Example: Let's look at an instance where we simply want to override one method from a parent class. The implementation is shown below. Output: Inside GrandChild Inside Parent Within the overridden method, calling the Parent's method The overridden methods may also invoke methods from the parent class. There are typically two ways to accomplish this. 1. Using Class name: Inside the overridden method, use the Parent classname-method to invoke methods from the Parent's class. Example: Output: Inside Parent Inside Child 2. Using Super (): The Super () function in Python allows us to refer to the parent class explicitly. It comes in handy when we need to call superclass functions. It gives us the proxy object to use "super" to refer to the parent class. Example Output: HEY !!!!!! JTP I am initialized (Class JSP3) HEY !!!!!! JTP I am initialized (Class JSP2) HEY !!!!!! JTP I am initialized (Class JSP1) Printing from class JTP3: 10 Printing from class JTP3: 11 Printing from class JTP3: 12 Next TopicPyGTK For GUI Programming |
We provides tutorials and interview questions of all technology like java tutorial, android, java frameworks
G-13, 2nd Floor, Sec-3, Noida, UP, 201301, India