python - 如何在类方法中生成新实例?
问题描述
我为我的文字冒险游戏创建了一个类,玩家可以在其中聘请申请人。但是一旦他们雇用了申请人,那个人就会成为雇员。因此,我希望该申请人实例成为我Employee
班级的实例。有没有办法做到这一点或更好的方法?
这是我的申请课程:
class Applicant:
def __init__(self, full_name, first_name, gender, previous_job, dob,
hire_score): # dob stands for date of birth.
self.full_name = full_name
self.first_name = first_name
self.gender = gender
self.previous_job = previous_job
self.dob = dob
self.hire_score = hire_score
这是我雇用申请人时的方法。在申请人追加到我的员工列表之前,我想自动为Employee
班级中的申请人创建一个新实例。
def hire(self):
print(f"{mPlayer.name}: Okay {self.first_name}, I will be hiring you.")
time.sleep(a)
print(f"{self.first_name}: Thank you so much!! I look forward to working and will not let you down.")
employee_list.append(self)
applicant_list.remove(self)
print(f"You have now hired {self.first_name}")
time.sleep(a)
print("You can view employee information and see their activities in the View Employee section.")
这是我的Employee
课:
class Employee:
def __init__(self, full_name, first_name, gender, previous_job, dob,
hire_score, position, schedule):
self.full_name = full_name
self.first_name = first_name
self.gender = gender
self.previous_job = previous_job
self.dob = dob
self.hire_score = hire_score
self.position = position
self.schedule = schedule
解决方案
我有几个建议给你。我将使用数据类来演示这些概念(参考:https ://docs.python.org/3/library/dataclasses.html )。
- 为什么不拥有相同的班级,但有一个标志表明您的人是雇员,例如:
from dataclasses import dataclass, asdict
@dataclass
class Person: # <- name a better name
is_employee: bool = False
- 使用继承。这两个类都有很多重复的字段,因此继承应该在您的示例中完美运行。
class Applicant:
name: str
dob: datetime.date
score: int
@dataclass
class Employee(Applicant):
position: str
schedule: object
然后,如果您有一个 实例applicant
,您可以轻松地从中创建一个employee
实例,而无需重复所有字段:
applicant = Applicant(name='John', ...)
employee = Employee(**asdict(applicant), position='Manager', ...)
推荐阅读
- python - 流光图像循环
- wireshark - 如何重放 Wireshark 捕获的数据包?
- javascript - node-postgres 传递自定义类型的数组
- node.js - 如何在对话流中使用用户会话?
- reactjs - 缺少必需参数:Spotify 克隆中的 redirect_uri
- r - 如何在R中将字符更改为数字向量
- django - 将项目放在 django 模板的顶部进行循环
- python - 使用 GeoDataFrames - 查找多边形的区域
- python - Webscraping:列表内的字典问题,带有重复数据的json
- python-3.x - 一周中的“最大值日”,并计算 Python 最高的每一天