Python classes inherit usage instance analysis

  • 2020-04-02 14:14:47
  • OfStack

This example demonstrates the use of python class inheritance. Share with you for your reference. Specific methods are as follows:


#!/usr/bin/python
# Filename: inherit.py

class SchoolMember:
  '''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),

class Teacher(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.salary

class Student(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.marks

t = 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 running output is as follows:


(Initialized SchoolMember: Mrs. Shrividya)
(Initialized Teacher: Mrs. Shrividya)
(Initialized SchoolMember: Swaroop)
(Initialized Student: Swaroop)
Name:"Mrs. Shrividya" Age:"40" Salary: "30000"
Name:"Swaroop" Age:"22" Marks: "75"

How does it work

To use inheritance, we use the name of the base class as a tuple after the class name when the class is defined. Then we notice that the basic class's s method is called exclusively with the self variable, so that we can initialize the basic class part of the object. This is important -- Python does not automatically call the constructor of a base class, you have to call it yourself.

We also observed that we prefixed the class name before the method call and then passed the self variable and other arguments to it.

Pay attention to When we use the tell method of the SchoolMember class, we use the Teacher and Student instances only as instances of SchoolMember.

Also, in this example, we call the tell method of the subtype, not the tell method of the SchoolMember class. To put it another way, Python always looks for methods of the corresponding type first, as in this case. If it can't find the corresponding method in the exported class, it starts looking in the base class one by one. A base class is specified in a tuple at the time the class is defined.

Comment on a term - if more than one class is listed in an inheritance tuple, it is called multiple inheritance.

I hope this article has helped you with your Python programming.


Related articles: