Inheritance in python


However classes can also inherit attributes from other classes.Hence,a subclass inherits from a superclass allowing you to make a generic superclass that is specialized via subclasses.The subclasses can override the logic in a superclass,allowing you to change the behaviour of you’r classes without changing the superclass at all.

1.Example for inheritance

>>>x=FirstClass()       #instance of FirstClass
>>>y=SecondClass()    #instance of SecondClass
>>>x.setdata("The boy called Brain.")
The boy called Brain.
Current value='42'

2.Example for Inheritance

class Person(object): 
# Constructor 
def __init__(self, name): = name 
# To get name 
def getName(self): 
# To check if this person is employee 
def isEmployee(self): 
return False 
# Inherited or Sub class (Note Person in bracket) 
class Employee(Person): 
# Here we return true 
def isEmployee(self): 
return True 
# Driver code 
emp = Person("Geek1") # An Object of Person 
print(emp.getName(), emp.isEmployee()) 
emp = Employee("Geek2") # An Object of Employee 
print(emp.getName(), emp.isEmployee()) 

Geek1 False
 Geek2 True 
Translate »