首页 > 解决方案 > 如何在子类中创建唯一属性?

问题描述

我正在尝试将 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()

标签: pythonoop

解决方案


您可以使用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

推荐阅读