继承:为了使用继承,基类的名称作为一个元组跟在类名称的后面;python支持多重继承。下面是一个关于继承的例子:
1 class SchoolMember:
2 '''Represent any school member.'''
3 def __init__(self, name, age):
4 self.name = name
5 self.age = age
6 print "Initializing a school member."
7
8 def tell(self):
9 '''Tell my details'''
10 print "Name: %s, Age: %s, " % (self.name, self.age),
11
12 class Teacher(SchoolMember):
13 '''Represent a teacher.'''
14 def __init__(self, name, age, salary):
15 SchoolMember.__init__(self, name, age)
16 self.salary = salary
17 print "Initializing a teacher"
18
19 def tell(self):
20 SchoolMember.tell(self)
21 print "Salary: %d" % self.salary
22
23 class Student(SchoolMember):
24 '''Represent a student.'''
25 def __init__(self, name, age, marks):
26 SchoolMember.__init__(self, name, age)
27 self.marks = marks
28 print "Initializing a student"
29
30 def tell(self):
31 SchoolMember.tell(self)
32 print "Marks: %d" % self.marks
33
34 print SchoolMember.__doc__
35 print Teacher.__doc__
36 print Student.__doc__
37
38 t = Teacher("Mr. Li", 30, 9000)
39 s = Student("Peter", 25, 90)
40
41 members = [t, s]
42
43 for m in members:
44 m.tell()
程序输出如下:
Represent any school member.
Represent a teacher.
Represent a student.
Initializing a school member.
Initializing a teacher
Initializing a school member.
Initializing a student
Name: Mr. Li, Age: 30, Salary: 9000
Name: Peter, Age: 25, Marks: 90
已有 22658 名学员学习以下课程通过考试
最需教育客户端 软件问题一手掌握
去 App Store 免费下载 iOS 客户端
点击加载更多评论>>