Person人类有姓名、性别和年龄属性,有吃饭和行走的方法;Student学生类是人类中的一种,学生类特有分数属性和学习、考试方法;Teacher老师类也是人类中的一种,老师类特有的成员有工资属性和讲课方法;Assistant助教既是学生类中的一种,也是老师类中的一种。
时间: 2024-05-23 08:14:35 浏览: 118
请问怎么设计这四种类的关系呢?
这四种类可以使用继承关系进行设计。即,Student和Teacher可以继承Person类的属性和方法,而Assistant则可以同时继承学生和老师的属性和方法。举例来说:
class Person:
def __init__(self, name, gender, age):
self.name = name
self.gender = gender
self.age = age
def eat(self):
print("Person is eating.")
def walk(self):
print("Person is walking.")
class Student(Person):
def __init__(self, name, gender, age, score):
super().__init__(name, gender, age)
self.score = score
def study(self):
print("Student is studying.")
def exam(self):
print("Student is taking an exam.")
class Teacher(Person):
def __init__(self, name, gender, age, salary):
super().__init__(name, gender, age)
self.salary = salary
def lecture(self):
print("Teacher is giving a lecture.")
class Assistant(Student, Teacher):
def __init__(self, name, gender, age, score, salary):
Student.__init__(self, name, gender, age, score)
Teacher.__init__(self, name, gender, age, salary)
def grade(self):
print("Assistant is grading papers.")
# 实例化
person = Person("Tom", "male", 28)
person.eat()
person.walk()
stu = Student("Li", "female", 20, 100)
stu.eat()
stu.walk()
stu.study()
stu.exam()
tea = Teacher("Wang", "male", 35, 10000)
tea.eat()
tea.walk()
tea.lecture()
asst = Assistant("Zhang", "female", 21, 99, 5000)
asst.eat()
asst.walk()
asst.study()
asst.exam()
asst.lecture()
asst.grade()
阅读全文