python中继承实现方法
派生类继承形式为:
class DerivedClass(BaseClass):
[注意]
[1] Python不会自动调用基类的constructor,要亲自专门调用它。在方法调用之前加上类名前缀,然后把self变量及其他参数传递给它。
[2] Python总是首先查找对应类型的方法,如果它不能在派生类中找到对应的方法,它才开始到基类中查找。
[3] 基类是在派生类定义时,在元组之中指明的。
[4] 如果在继承元组中列了一个以上的类,那么它就被称作多重继承。
#! /usr/bin/python # Filename: inherit.py # 2010-7-14 wcdj # www.jb200.com 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), # note, this comma 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('Mr. Young', 40, 30000) s=Student('wcdj', 22, 75) print # prints a blank line members=[t, s] for i in members: i.tell() # works for both Teachers and Students ######### # output ######### >>> (Initialized SchoolMember:Mr. Young) (Initialized Teacher:Mr. Young) (Initialized SchoolMember:wcdj) (Initialized Student:wcdj) Name:"Mr. Young" Age:"40" Salary:"30000" Name:"wcdj" Age:"22" Marks:"75"