代碼:
#! /usr/bin/python<br /># Filename: inherit.py<br /># Author: yanggang</p><p>class SchoolMember:<br /> def __init__(self,name,age):<br /> self.name = name<br /> self.age = age<br /> print 'init SchoolMember: ', self.name</p><p> def tell(self):<br /> print 'name:%s; age:%s' % (self.name, self.age)</p><p>class Teacher(SchoolMember):<br /> def __init__(self,name,age,salary):<br /> SchoolMember.__init__(self,name,age)<br /> self.salary = salary<br /> print 'init Teacher: ', self.name</p><p> def tell(self):<br /> SchoolMember.tell(self)<br /> print 'salary: ', self.salary</p><p>class Student(SchoolMember):<br /> def __init__(self,name,age,marks):<br /> SchoolMember.__init__(self,name,age)<br /> self.marks = marks<br /> print 'init Student: ', self.name</p><p> def tell(self):<br /> SchoolMember.tell(self)<br /> print 'marks: ', self.marks</p><p>t = Teacher('yanggang', 20, 1000)<br />s = Student('liming', 12, 86)<br />members = [t,s]</p><p>print</p><p>for member in members:<br /> member.tell()<br />
結果:
[work@db-testing-com06-vm3.db01.baidu.com python]$ python inherit.py
init SchoolMember: yanggang
init Teacher: yanggang
init SchoolMember: liming
init Student: liming
name:yanggang; age:20
salary: 1000
name:liming; age:12
marks: 86