位置:首頁 > 軟件操作教程 > 編程開發(fā) > Python > 問題詳情

python 類的繼承

提問人:楊紫紅發(fā)布時間:2020-11-20

繼承:為了使用繼承,基類的名稱作為一個元組跟在類名稱的后面;python支持多重繼承。下面是一個關(guān)于繼承的例子:

 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

繼續(xù)查找其他問題的答案?

相關(guān)視頻回答
回復(fù)(0)
返回頂部