欢迎访问 生活随笔!

生活随笔

当前位置: 首页 > 编程语言 > python >内容正文

python

Python---已知Person类,继承Person类生成Teacher类(增加参数:科目)和Student类(增加参数:专业)。

发布时间:2025/5/22 python 44 豆豆
生活随笔 收集整理的这篇文章主要介绍了 Python---已知Person类,继承Person类生成Teacher类(增加参数:科目)和Student类(增加参数:专业)。 小编觉得挺不错的,现在分享给大家,帮大家做个参考.

题目:已知Person类,继承Person类生成Teacher类(增加参数:科目)和Student类(增加参数:专业)。

已知Person类如下:

class Person(object):# Person类的构造方法,参数:姓名,年龄,性别def __init__(self,name='',age=20,sex='man'):self.setName(name)self.setAge(age)self.setSex(sex)# setName方法用于设置姓名def setName(self, name):if not isinstance(name, str):print('name must be string.')returnself.__name=name# setAge方法用于设置年龄def setAge(self, age):if not isinstance(age, int):print('age must be integer.')returnself.__age=age# setSex方法用于设置性别def setSex(self, sex):if sex not in ('man', 'woman'):print('sex must be "man" or "woman"')returnself.__sex=sex# show方法用于显示姓名,年龄,性别def show(self):print('Name:', self.__name)print('Age:', self.__age)print('Sex:', self.__sex)

Teacher类继承Person类,新增参数:科目:

class Teacher(Person):# Teacher类的构造方法,参数:姓名,年龄,性别,科目(前三个参数继承自父类)def __init__(self,name='',age=30,sex='man',department='Computer'):super(Teacher,self).__init__(name,age,sex)##or,use another method like:Person.__init__(name,age,sex)self.setDepartment(department)# setDepartment方法用于设置科目def setDepartment(self,department):if not isinstance(department,str):print('department must be a string.')returnself.__department=department# show方法用于显示姓名,年龄,性别,科目def show(self):super(Teacher, self).show()print('Department:',self.__department)

Student类继承Person类,新增参数:专业

class Student(Person):# Student类的构造方法,参数:姓名,年龄,性别,专业(前三个参数继承自父类)def __init__(self,name='',age=30,sex='man',major='Software'):super(Student,self).__init__(name,age,sex)##or,use another method like:Person.__init__(name,age,sex)self.setMajor(major)# setMajor方法用于设置专业def setMajor(self,major):if not isinstance(major,str):print('major must be a string.')returnself.__major=major# show方法用于显示姓名,年龄,性别,专业def show(self):super(Student, self).show()print('Major:',self.__major)

main函数如下:

if __name__ == '__main__':# 父类Person对象zhangsan=Person('zhang San',10,'man')zhangsan.show()# 子类Teacher对象lisi=Teacher('Li Si',30,'woman','Math')lisi.show()# 子类Student对象wangwu=Student('Wang Wu',18,'man','Software')wangwu.show()

总结

以上是生活随笔为你收集整理的Python---已知Person类,继承Person类生成Teacher类(增加参数:科目)和Student类(增加参数:专业)。的全部内容,希望文章能够帮你解决所遇到的问题。

如果觉得生活随笔网站内容还不错,欢迎将生活随笔推荐给好友。