Python Method Overriding is another important feature in python programming. Learn all about method overriding in Python here.
Python Incompatibilities: Basic method overriding
Here is an example of basic overriding in Python (for the sake of clarity and compatibility with both Python 2 and 3, using new style class and print with ()):
p = Parent()
c = Child()
python basic_override.py Hello!
Parent Hello! Child
When the Child class is created, it inherits the methods of the Parent class. This means that any methods that the parent class has, the child class will also have. In the example, the introduce is defined for the Child class because it is defined for Parent, despite not being defined explicitly in the class definition of Child.
In this example, the overriding occurs when Child defines its own print_name method. If this method was not declared, then c.print_name() would have printed "Parent". However, Child has overridden the Parent's definition of print_name, and so now upon calling c.print_name(), the word "Child" is printed.
Must Read Python Interview Questions
200+ Python Tutorials With Coding Examples
Other Python Tutorials
- What is Python?
- Python Advantages
- Python For Beginners
- Python For Machine Learning
- Machine Learning For Beginners
- 130+ Python Projects With Source Code On GitHub