我很难创建Class-Inheritance的python代码。父类是“人员类”,子类是“学生类”和“教授类”。
我花了很多时间,但这很难理解。我做了1个父类,2个子类和方法。 我认为我的很多代码都需要修改,我不知道如何解决。
class Person:
def __init__(self,name,age,department):
self.name = name
self.age = age
self.department = department
def get_name():
return self.name
class Student(Person):
def __init__(Person,i_d,GPA,advisor):
self.Person = Person
self.i_d = i_d
self.GPA = GPA
self.advisor = advisor
def print_info():
print("Name: %s, Age: %d, Department: %s, Advisor: %s " %(Person.name,Person.age,Person.department,Student.advisor))
def reg_advisor():
return Professor.name
class Professor(Person):
def __init__(self,position,laboratory,student):
self.position = position
self.laboratory = laboratory
self.student = student
def print_info():
print("Name: %s, Age: %d, Department: %s, Student: %s and %s " %(Person.name,Person.age,Person.department,Professor.student))
def reg_student():
return Student.name
Stu1 = Student("David", 30, "Computer", 20001234, 4.5)
Stu2 = Student("Tom", 30, "Computer", 20001234, 4.5)
prof1 = Professor("Andrew", 55, "Computer", "Full", "DT") # The last element is the list of student.
stu1.reg_advisor(prof1)
stu2.reg_advisor(prof1)
prof1.reg_student(stu1)
prof1.reg_student(stu2)
stu1.print_info()
stu2.print_info()
prof1.print_info()
结果应为:
# Name: David, Age: 30, Department: Computer, Advisor: Andrew)
# Name: Tom, Age: 30, Department: Computer, Advisor: Andrew)
# Name: Andrew, Age: 55, Department: Computer, Students: David and Tom)
我更希望不要添加或删除方法。
任何帮助将不胜感激。