what is inheritance in python code example
Example 1: what is a child inheritance in python with example
class A:
def feature1(self):
print('Feature 1 in process...')
def feature2(self):
print('Feature 2 in process...')
class B:
def feature3(self):
print('Feature 3 in process...')
def feature4(self):
print ('Feature 4 in process...')
a1 = A()
a1.feature1()
a1.feature2()
a2 = B()
a2.feature3()
a2.feature4()
class A:
def feature1(self):
print('Feature 1 in process...')
def feature2(self):
print('Feature 2 in process...')
class B(A):
def feature3(self):
print('Feature 3 in process...')
def feature4(self):
print ('Feature 4 in process...')
a1 = A()
a1.feature1()
a1.feature2()
a2 = B()
a2.feature3()
a2.feature4()
Example 2: python inheritance
class Person:
name = ""
def __init__(self, personName):
self.name = personName
def showName(self):
print(self.name)
class Student(Person):
studentClass = ""
def __init__(self, studentName, studentClass):
Person.__init__(self, studentName)
self.studentClass = studentClass
def getStudentClass(self):
return self.studentClass
person1 = Person("Dave")
person1.showName()
student1 = Student("Mary", "Maths")
print(student1.getStudentClass())
student1.showName()
Example 3: inheritance in python
class Parent:
BloodGroup = 'A'
Gender = 'Male'
Hobby = 'Chess'
class Child(Parent):
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()
Example 4: Inheritance example python
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()
Example 5: inheritance in python 3 example
class Robot:
def __init__(self, name):
self.name = name
def say_hi(self):
print("Hi, I am " + self.name)
class PhysicianRobot(Robot):
def say_hi(self):
print("Everything will be okay! ")
print(self.name + " takes care of you!")
y = PhysicianRobot("James")
y.say_hi()
Example 6: inheritance in python 3 example
class Robot:
def __init__(self, name):
self.name = name
def say_hi(self):
print("Hi, I am " + self.name)
class PhysicianRobot(Robot):
pass
x = Robot("Marvin")
y = PhysicianRobot("James")
print(x, type(x))
print(y, type(y))
y.say_hi()