【发布时间】:2021-06-20 03:30:29
【问题描述】:
我正在尝试将 Person 类扩展到 Student 和 Employee 子类。有没有一种方法可以分别为 Student 和 Employee 创建独特的属性 Course 和 Department >无需重复使用__init__()?
代码如下:
class Person():
def __init__(self, name, address):
self.name = name
self.address = address
class Student(Person):
stud_id = 0
def __init__(self, course):
Student.stud_id += 1
self.course=course
def show(self):
print(self.stud_id)
print(self.name)
print(self.address)
print(self.course)
class Employee(Person):
emp_id = 0
def __init__(self, department):
Employee.emp_id += 1
self.department=department
def show(self):
print(self.emp_id)
print(self.name)
print(self.address)
print(self.department)
stud = Student("Josh", "Philippines", "StudCourse")
stud.show()
emp = Employee("Claire", "Australia", , "EmpDepartment")
emp.show()
【问题讨论】:
-
听起来您只想在 Student 和 Employee
__init__函数中分配给self.course和self.department。另外,我认为您的stud_id和emp_id变量不会按照您的意图进行。您没有为每个学生和员工设置唯一的 id,而是在计算有多少人。 -
另外请注意
__int__中的错字(缺少i) -
@Tomerikoo,在那篇文章中使用 __init__() 属性名称和电话被重复声明/覆盖的子类中提出的解决方案是我想要问的。我们真的需要在子类中重复声明Parent类的属性吗?因为我正在尝试为子类添加一个唯一属性 - 分别为 Student 和 Employee 子类的课程和部门。
-
它们在问题中重复出现。您是否看过第一个建议如何避免这种情况的答案?