Python Method overriding:
Parent class:
class pclass:
... var1="Im in parent class"
... def add(self, number1, number2):
... return number1 + number2
Child Class:
class cclass(pclass):
... var1="Im in parent class"
... def add(self, number1, number2, number3):
... return number1 + number2+number3
Here, we override the "add" method of parent class in the child class. See the output
Output:
>> c = class()
>> c.add(1,2,3)
>> 6
So, it uses only the add method of the child class, not the parent class
Note: Child class is also called as sub class
Why overriding is required?
One reason for overriding parent's methods is because you may want special or different functionality in your subclass.
Parent class:
class pclass:
... var1="Im in parent class"
... def add(self, number1, number2):
... return number1 + number2
Child Class:
class cclass(pclass):
... var1="Im in parent class"
... def add(self, number1, number2, number3):
... return number1 + number2+number3
Here, we override the "add" method of parent class in the child class. See the output
Output:
>> c = class()
>> c.add(1,2,3)
>> 6
So, it uses only the add method of the child class, not the parent class
Note: Child class is also called as sub class
Why overriding is required?
One reason for overriding parent's methods is because you may want special or different functionality in your subclass.
No comments:
Post a Comment