[Tutor] Simple Question On A Method (in subclass)

Alan Gauld alan.gauld at btinternet.com
Sun Oct 23 01:24:36 CEST 2011


On 22/10/11 23:10, Chris Kavanagh wrote:

> My question is regarding the tell methods in the subclasses,the code
> {SchoolMember.tell(self)}, in the class Teacher & Student. I just don't
> understand what this is doing? Calling the first method {def tell} from
> the parent class, I assume?

Thats right, the child class is calling its parent class method.
This saves the child class from copying the code in the parent.

> There is already a print statement in each of the subclass {def tell}
 > showing details, why call another print statement

In this case it doesn't same much code (a few charactrs less) but with a 
more complex method it couyld be a lot iof saving. However, that's not 
the only advantage. If you want to change the format of the parent 
message you only need to change the parent code, the children get the 
change for free. Also if you copied the code into each child there is a 
real risk that you'd get the formatting slightly different. Then when 
you try to call the tell() method of a list of objects, some parents and 
some children the outputs would look different - thats messy.

> class SchoolMember:
> def tell(self):
> '''Tell my details.'''
> print 'Name:"%s" Age:"%s"' % (self.name, self.age),
>
> class Teacher(SchoolMember):
> def tell(self):
> SchoolMember.tell(self)
> print 'Salary: "%d"' % self.salary
>
> class Student(SchoolMember):
> 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()

> Name:"Mrs. Shrividya" Age:"40" Salary: "30000"
> Name:"Swaroop" Age:"22" Marks: "75"

HTH

-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/



More information about the Tutor mailing list