This example describes the Python class inheritance usage. Share to everyone for your reference. Here's how:
#!/usr/bin/python# Filename:inherit.pyclass Schoolmember: "represents any school member." def __init__ (self, Name, age): Self.name = name Self.age = Age print ' (Initialized schoolmember:%s) '% Self.name def tell: "Tell my details." print ' Name: '%s ' Age: '%s ' '% (Self.name, self.age), Class Teacher (Schoolmember): ' Represents a Teacher. ' def __init__ (self, name, age, salary): schoolmember.__init__ (self, name, age) Self.salary = salary print ' (Initial ized Teacher:%s) '% Self.name def tell: Schoolmember.tell (self) print ' Salary: '%d ' '% self.salaryclass Student (Schoolmember): "Represents a student." def __init__ (self, name, age, marks): schoolmember.__init__ (self, name, age) Self.marks = Marks print ' (Initialize D Student:%s) '% Self.name def tell (self): Schoolmember.tell (self) print ' Marks: '%d ' '% Self.markst = Teacher (' Mrs. Shrividya ', 40,30000) s = Student (' Swaroop ', 22,75) members = [T, s]for member in Members:member. Tell () # Works for both Teachers and Students
The results of the run output are as follows:
(Initialized Schoolmember:mrs. Shrividya) (Initialized Teacher:mrs. Shrividya) (Initialized Schoolmember:swaroop) (Initialized Student:swaroop) Name: "Mrs. Shrividya" Age: "Salary:" 30000 "Name:" Swaroop "Age:" Marks ":" 75 "
How it works
To use inheritance, we take the name of the base class as a tuple following the class name when the class is defined. We then notice that 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. This is very important--python does not automatically invoke the constructor of the base class, you have to call it yourself specifically.
We also observed that we add the class name prefix before the method call, and then pass the self variable and other parameters to it.
Note that when we use the Tell method of the Schoolmember class, we take the instance of teacher and student only as an instance of Schoolmember.
Also, in this example, we call the Tell method of the subtype, not the Tell method of the Schoolmember class. It can be understood that Python is always looking for a method of the corresponding type first, in this case. If it cannot find the corresponding method in the export class, it begins to look up one by one in the base class. The base class is specified in the tuple when the class is defined.
A comment for a term-- if more than one class is listed in an inheritance tuple, it is called multiple inheritance .
Hopefully this article will help you with Python programming.