Python Overriding
- It is nothing but rewriting super class method in sub class.
- Rules to override
- Class must be inherited
- Method name must be same
- Same no. of parameters should be there.
- Python provides
- Constructor Overriding
Rewriting the constructor in child class.
#program for constructor overriding
class A :
def __init__(self):
print("This is class A constructor")
class B(A) :
def __init__(self):
print("This is class B constructor")
a = A()
b = B()
#output
This is class A constructor
This is class B constructor
How to call Super Class constructor in sub Class ?
#program for calling super class constructor in sub class
class A :
def __init__(self):
print("This is class A constructor")
class B(A) :
def __init__(self):
super().__init__()
print("This is class B constructor")
b = B() # creating object to class b
#output
This is class A constructor
This is class B constructor
- Method Overriding
#program for Method Overriding
class A :
def __init__(self):
print("This is class A constructor")
def add(self, a, b):
print("add function of class A")
return a+b;
class B(A) :
def add(self, a, b):
print("add function of class B")
return a-b;
b = B()
c = b.add(10, 5)
print("c :", c)
#output
This is class A constructor
add function of class B
c : 5
Comments
Post a Comment