【问题标题】:How to create unique property in a child class? [duplicate]如何在子类中创建唯一属性? [复制]
【发布时间】:2021-06-20 03:30:29
【问题描述】:

我正在尝试将 Person 类扩展到 Student 和 Employee 子类。有没有一种方法可以分别为 StudentEmployee 创建独特的属性 CourseDepartment >无需重复使用__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.courseself.department。另外,我认为您的 stud_idemp_id 变量不会按照您的意图进行。您没有为每个学生和员工设置唯一的 id,而是在计算有多少人。
  • 另外请注意__int__中的错字(缺少i
  • @Tomerikoo,在那篇文章中使用 __init__() 属性名称和电话被重复声明/覆盖的子类中提出的解决方案是我想要问的。我们真的需要在子类中重复声明Parent类的属性吗?因为我正在尝试为子类添加一个唯一属性 - 分别为 Student 和 Employee 子类的课程和部门。
  • 它们在问题中重复出现。您是否看过第一个建议如何避免这种情况的答案?

标签: python oop


【解决方案1】:

您可以使用super()。请看下面:

class Person():
   def __init__(self, name, address):
       self.name=name
       self.address=address

class Student(Person):
   stud_id=0
   def __init__(self, name, address, course):
       self.stud_id = Student.stud_id
       Student.stud_id +=1
       super().__init__(name, address)
       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, name, address, department):
       self.emp_id = Employee.emp_id
       Employee.emp_id +=1
       super().__init__(name, address)
       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()

stud2 = Student("Josh 2", "Philippines 2", "StudCourse 2")
stud2.show()

emp2 = Employee("Claire 2", "Australia 2", "EmpDepartment 2")
emp2.show()

这给了我以下输出:

0
Josh
Philippines
StudCourse
0
Claire
Australia
EmpDepartment
1
Josh 2
Philippines 2
StudCourse 2
1
Claire 2
Australia 2
EmpDepartment 2

【讨论】:

    猜你喜欢
    • 2011-03-13
    • 2010-11-26
    • 2010-10-15
    • 2020-08-11
    • 1970-01-01
    • 1970-01-01
    • 2014-12-20
    • 2021-12-15
    • 2012-07-26
    相关资源
    最近更新 更多