python: Inheritance
class Student:
def __init(self, name, school):
self.name = name
self.school = school
self.marks = []
def average(self):
return sum(self.marks) / len(self.marks)
class WorkingStudent(Student): # WorkingStudent() is a child of Student()
def __init__(self, name, school, salary):
super().__init__(name, school) # parent class of Student()
self.salary = salary
sarah = WorkingStudent('Sarah', 'Oxford', 10)
print(sarah.salary)
sarah.marks.append(30)
sarah.marks.append(28)
print(sarah.average())
# creating parent class
class Parent:
BloodGroup = 'A'
Gender = 'Male'
Hobby = 'Chess'
# creating child class
class Child(Parent): # inheriting parent class
BloodGroup = 'A+'
Gender = 'Female
def print_data():
print(BloodGroup, Gender, Hobby)
# creating object for child class
child1 = Child()
# as child1 inherits it's parent's hobby printed data would be it's parent's
child1.print_data()
# Python code to demonstrate how parent constructors
# are called.
# parent class
class Person( object ):
# __init__ is known as the constructor
def __init__(self, name, idnumber):
self.name = name
self.idnumber = idnumber
def display(self):
print(self.name)
print(self.idnumber)
# child class
class Employee( Person ):
def __init__(self, name, idnumber, salary, post):
self.salary = salary
self.post = post
# invoking the __init__ of the parent class
Person.__init__(self, name, idnumber)
# creation of an object variable or an instance
a = Employee('Rahul', 886012)
# calling a function of the class Person using its instance
a.display()
class Parent:
def abc(self):
print("Parent")
class LeftChild(Parent):
def pqr(self):
print("Left Child")
class RightChild(Parent):
def stu(self):
print("Right Child")
class GrandChild(LeftChild,RightChild):
def xyz(self):
print("Grand Child")
obj1 = LeftChild()
obj2 = RightChild()
obj3 = GrandChild()
obj1.abc()
obj2.abc()
obj3.abc()