Python Inheritance
# Inheritance
# Multi-level inheritance
# Multiple inheritance
class Person: # Grandparent class ---> Multi-level inheritance
def __init__(self, first_name, last_name, age):
self.first_name = first_name
self.last_name = last_name
self.age = age
def info(self):
print(f"{self.first_name} {self.last_name} is {self.age} years old.")
class Student(Person): # Parent class
def __init__(self, first_name, last_name, age, user_class):
super().__init__(first_name,last_name,age)
self.user_class = user_class
def learn(cls):
print("User can learn.")
class Teacher(Student): # Child class
def __init__(self, first_name,last_name,age,user_class,subject):
# Student.__init__(self,first_name,last_name,age) # uncommon
super().__init__(first_name,last_name,age,user_class)
self.subject = subject
def teach(cls):
print("User can teach.")
p1 = Person("Priya","Singh",19)
p2 = Person("Sohan","Sharma",36)
s1 = Student("Adrika", "Bhadauria",14,9)
s2 = Student("Anika", "Singh",3,1)
t1 = Teacher("Riya","Singh",26,4,"English")
t2 = Teacher("Rohan","Sharma",39,6,"Maths")
print(t1.info())
print(t2.info())
print(t1.first_name)
print(t2.first_name)
class A:
def A_func(self):
print("This function is of class A.")
def hello(self):
print("Hello! From class A.")
class B:
def B_func(self):
print("This function is of class B.")
def hello(self):
print("Hello! From class B.")
class C(A,B): # Multiple inheritance
pass
obj = C()
obj.A_func()
obj.B_func()
obj.hello()
Post a Comment