Inheritance
class Parent:
def __init__(self):
print("parent class")
class child(Parent):
def __init__(self):
print("child class")
# Start class names with capital lettes or we use camel case
class SchoolMember:
def __init__(self, name):
[Link] = name
class Student(SchoolMember): # inheriting parent class
def __init__(self, name, grade):
[Link] = grade
class Staff(SchoolMember):
def __init__(self, name, salary):
[Link] = salary
class Teacher(Staff):
def __init__(self, name, salary, subject):
[Link] = subject
above example displays inheritence tree like this
s1 = Student("Krishna", "A")
type(s1)
__main__.Student
[Link]
'A'
[Link] # class inherited still cannot use the properties
---------------------------------------------------------------------------
AttributeError Traceback (most recent call last)
<ipython-input-14-58cbae705711> in <cell line: 1>()
----> 1 [Link] # class inherited still cannot use the properties
AttributeError: 'Student' object has no attribute 'name'
problem is we never called the __init__() function of the parent class inside the child.
we can use super() method to directly call the methods of parent class
# Start class names with capital lettes or we use camel case
class SchoolMember:
def __init__(self, name):
[Link] = name
class Student(SchoolMember):
def __init__(self, name, grade):
# SchoolMember.__init__(self, name)
super().__init__(name)
# super automatically corresponds to the direct parent class
[Link] = grade
class Staff(SchoolMember):
def __init__(self, name, salary):
super().__init__(name)
[Link] = salary
class Teacher(Staff):
def __init__(self, name, salary, subject):
super().__init__(name, salary)
[Link] = subject
s1 = Student("Sharath", "A")
t1 = Teacher("Bipin", 10, "Python")
[Link], [Link], [Link]
('Bipin', 10, 'Python')
keyboard_arrow_down Multiple Inheritence
class A:
def __init__(self, a):
self.a = a
class B:
def __init__(self, b):
self.b = b
# C inherits from both A and B
class C(A, B):
def __init__(self, a, b, c):
A.__init__(self, a)
B.__init__(self, b)
self.c = c
c1 = C(1,2,3)
c1.c