面向对象编程-继承实例

Posted bit-taozhen

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了面向对象编程-继承实例相关的知识,希望对你有一定的参考价值。

 1 #!/usr/bin/env python
 2 # -*- coding:utf-8 -*-
 3 # Author:James Tao
 4 
 5 class School(object):
 6     def __init__(self,name,addr):
 7         self.name=name
 8         self.addr=addr
 9         self.students=[]
10         self.teachers=[]
11 
12     def enroll(self,stu_obj):
13         print(为学员%s办理注册手续 % stu_obj.name)
14         self.students.append(stu_obj)
15 
16     def employ(self,tea_obj):
17         print(为教师%s办理注册手续 % tea_obj.name)
18         self.teachers.append(tea_obj)
19 
20 class SchoolMember(object):
21     def __init__(self,name,age,sex):
22         self.name=name
23         self.age=age
24         self.sex=sex
25     def tell(self):
26         print(‘‘‘----
27         ‘‘‘)
28 
29 class Teacher(SchoolMember):
30     def __init__(self, name, age, sex, salary, course):
31         super(Teacher, self).__init__(name, age, sex)
32         self.salary = salary
33         self.course=course
34 
35     def tell(self):
36         print(‘‘‘
37         ----info of {_name}----
38         Name:{_name}
39         Age:{_age}
40         Sex:{_sex}
41         Salary:{_salary}
42         Course:{_course}
43         ‘‘‘.format(_name=self.name, _age=self.age, _sex=self.sex, _salary=self.salary, _course=self.course))
44 
45     def teach(self):
46         print(%s is teaching course [%s] % (self.name, self.course))
47 
48 class Student(SchoolMember):
49     def __init__(self,name,age,sex,stu_id,grade):
50         super(Student,self).__init__(name, age, sex)
51         self.stu_id = stu_id
52         self.grade=grade
53 
54     def tell(self):
55         print(‘‘‘
56         ----info of {_name}----
57         Name:{_name}
58         Age:{_age}
59         Sex:{_sex}
60         Stu_id:{_stu_id}
61         Grade:{_grade}
62         ‘‘‘.format(_name=self.name, _age=self.age, _sex=self.sex, _stu_id=self.stu_id, _grade=self.grade))
63 
64     def learn(self):
65         print(%s is learning in grade [%s] % (self.name, self.grade))
66 
67     def pay_tuition(self,amount):
68         print(%s has paid tuition for $%s % (self.name,amount))
69 
70 school=School(BIT,中关村)
71 t1=Teacher(Wang,40,F,200000,BD)
72 s1=Student(Tao,24,M,3120180812,BD)
73 school.enroll(s1)
74 school.employ(t1)
75 t1.tell()
76 s1.tell()
77 print(school.students)
78 school.students[0].learn()
79 school.teachers[0].teach()

运行结果:

技术图片

以上是关于面向对象编程-继承实例的主要内容,如果未能解决你的问题,请参考以下文章

面向对象编程-继承实例

VSCode自定义代码片段——JS中的面向对象编程

面向对象编程思想 以及 封装,继承,多态 和 python中实例方法,类方法,静态方法 以及 装饰器

Python面向对象编程之继承与多态详解

VSCode自定义代码片段9——JS中的面向对象编程

JavaScript面向对象编程(原型类基础)