python - 如何在子类中创建唯一属性?
问题描述
我正在尝试将 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()
解决方案
您可以使用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
推荐阅读
- java - DriverManager 找不到,红色下划线提示我创建类DriverManager
- javascript - onclick 事件在表单结束标记后不起作用
- python - 抑制 sklearn.metrics.plot_confusion_matrix 中的科学记数法
- python - 数据扩展 R/Python
- laravel - 如何在 laravel 应用程序中保存不同的域,并且该应用程序可以从该域访问
- list - 在对象上创建 MonoBehaviours 列表
- multithreading - Data.Binary encodeFile 似乎不是线程安全的 - 文件损坏?
- c# - 删除不必要的 NuGet 引用
- openapi - 如何在 OpenAPI 3.0 中定义具有两个可选参数的路径?
- javascript - 导出带有下拉列表的html表,使用jquery进行excel