Inheritance: Type and subtype relationships between classes
Code reuse: The Schoolmember class is referred to as the base class or superclass, while the teacher and student classes are referred to as export classes or subclasses
#!/usr/bin/python#filename:inherit.pyclassSchoolmember:'represents any school member.'def __init__ (self,name,age): Self.name=name Self.age=Age Print'(Initialized schoolmember:%s)'%Self.name def tell (self):'Tell my details.'Print'Name: '%s ' Age: '%s ''%(self.name,self.age)classTeacher (schoolmember):'represents a teacher.'def __init__ (self,name,age,salary): schoolmember.__init__ (self,name,age) self.salary=Salary Print'(Initialized teacher:%s)'%Self.name def tell (self): Schoolmember.tell (self) Print'Salary: "%d"'%self.salaryclassStudent (schoolmember):'represents a student.'def __init__ (self,name,age,marks): schoolmember.__init__ (self,name,age) Self.marks=Marks Print'(Initialized student:%s)'%Self.name def tell (self): Schoolmember.tell (self) Print'Marks: "%d"'%Self.markst=teacher ('Mrs.shrividya', +,30000) s=student ('Swaroop', A, the) Print #prints a blank linemembers=[T,s] forMemberinchMembers:member.tell ()
Results:
( Initialized SchoolMember:Mrs.Shrividya) (Initialized Teacher:Mrs.Shrividya) (Initialized schoolmember:swaroop) (Initialized Student:swaroop) Name:"Mrs.shrividya"Age:" +"Salary:"30000"Name:"Swaroop"Age:" A"Marks:" the"
Note: in order to use inheritance, the name of the base class as a tuple follows the class name when the class is defined.
The __init__ method of the base class is specifically called with the self variable, so that we can initialize the basic class part of the object.
Remember:python does not automatically invoke the constructor of the base class, it needs to be specifically called in person.
Concise Python Tutorial Seven----object-oriented programming (bottom)