Python by Swaroop C H - HTML preview

PLEASE NOTE: This is an HTML preview only and some elements such as links or page numbers may be incorrect.
Download the book in PDF, ePub, Kindle for a complete version.

Using Inheritance

Example 11.5. Using Inheritance

#!/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)
print # prints a blank line
members = [t, s]
for member in members:
member.tell() # works for both Teachers and Students

Output

$ python inherit.py
(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 It Works

To use inheritance, we specify the base class names in a tuple following the class name in the class definition. Next, we observe that the__init__ method of the base class is explicitly called using the self variable so that we can initialize the base class part of the object. This is very important to remember - Python does not automatically call the constructor of the base class, you have to explicitly call it yourself.

We also observe that we can call methods of the base class by prefixing the class name to the method call and then pass in theself variable along with any arguments.

 

Notice that we can treat instances ofTeacher orStudent as just instances of theSchoolMember when we use thetell method of theSchoolMember class.

Also, observe that the tell method of the subtype is called and not thetell method of theSchoolMember class. One way to understand this is that Python always starts looking for methods in the type, which in this case it does. If it could not find the method, it starts looking at the methods belonging to its base classes one by one in the order they are specified in the tuple in the class definition.

A note on terminology - if more than one class is listed in the inheritance tuple, then it is called multiple inheritance.