Object Oriented Python

Object Oriented Python

Python Overriding Methods?

Method overriding is an important concept in object-oriented programming. Method overriding allows us to redefine a method by overriding it. For method overriding, we must satisfy two conditions:

There should be a parent-child relationship between the classes. Inheritance is a must.

The name of the method and the parameters should be the same in the base and derived class in order to override it.

What will happen when the method in the base and derived class are the same. Let’s see an example of this.

Example

class A:
    def method(self):
        print("A class")
class B(A):
    def method(self):
        print("B class")
b = B()
b.method()

Output: B class

Here, the B class has inherited the A class and we have the same function in both classes method(). Since the name and parameters are the same, the derived class overrides the method of the base class and when we call the method() the B class method is called. This is known as method overriding.

Python Overloading Methods?

If you have some experience with object-oriented programming or other languages like C/C++ or Java then you might have used method overloading. That is why it is important to understand that Python doesn’t support method overloading.

Example

def getDetails():
    print("Name: Default")
def getDetails(name):
    print("Name:", name)
getDetails("Siri")
getDetails()

Output: Name: Siri

Traceback (most recent call last): File “C:\Users\prahlad\AppData\Local\Programs\Python\Python38-32\test.py”, line 8, in

getDetails() TypeError: getDetails() missing 1 required positional argument: ‘name’

As you can see, the getDetails(“Siri”) function got executed but the getDetails() was not executed. This is because Python overwrites the function with the same name and the latter function is used.

Did you find this article valuable?

Support Prahlad Inala by becoming a sponsor. Any amount is appreciated!