How to Call Method of a Particular Super Class:
We can use the following approaches
1) super(D, self).m1() It will call the m1() method of the superclass of D.
2) A.m1(self)
It will call the A class m1() method
#supermethod
class A:
def m1(self):
print('A class Method')
class B(A):
def m1(self):
print('B class Method')
class C(B):
def m1(self):
print('C class Method')
class D(C):
def m1(self):
print('D class Method')
class E(D):
def m1(self):
A.m1(self)
e = E ()
e.m1()
Output: A class Method
Various Important Points about super():
1: From child class, we are not allowed to access parent class instance variables by
using super(), Compulsory we should use self only.
But we can access parent class static variables by using super().
class P:
a=10
def __init__(self):
self.b=20
class C(P):
def m1(self):
print(super().a)#valid
print(self.b)#valid
print(super().b)#invalid
c=C()
c.m1()
Output:
10
20
AttributeError: 'super' object has no attribute 'b'
2: From the child class constructor and instance method, we can access the parent class
instance method, static method, and class method by using super()
class P:
def __init__(self):
print('Parent Constructor')
def m1(self):
print('Parent instance method')
@classmethod
def m2(cls):
print('Parent class method')
@staticmethod
def m3():
print('Parent static method')
class C(P):
def __init__(self):
super().__init__()
super().m1()
super().m2()
super().m3()
def m1(self):
super().__init__()
super().m1()
super().m2()
super().m3()
c=C()
c.m1()
Output:
Parent Constructor
Parent instance method
Parent class method
Parent static method
Parent Constructor
Parent instance method
Parent class method
Parent static method
3: From child class, the class method we cannot access parent class instance methods
and constructors by using super() directly(but indirectly possible). But we can access
parent class static and class methods.
class P:
def __init__(self):
print('Parent Constructor')
def m1(self):
print('Parent instance method')
@classmethod
def m2(cls):
print('Parent class method')
@staticmethod
def m3():
print('Parent static method')
class C(P):
@classmethod
def m(cls):
#super().__init__()--->invalid
#super().m1()--->invalid
super().m2()
super().m3()
C.m()
Output:
Parent class method
Parent static method
Comments
Post a Comment