如何在类方法内部生成新实例



我为我的文本冒险游戏创建了一个类,玩家可以在其中雇佣申请人。但一旦他们雇佣了申请人,这个人就会成为一名雇员。因此,我希望该申请人实例成为我的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

您需要执行以下操作:

print(f"{self.first_name}: Thank you so much!! I look forward to working and will not let you down.")
new_employee = Employee(full_name, first_name, gender, previous_job, dob, hire_score, position, schedule)
employee_list.append(self)

您可能还希望不附加申请人记录,而是将最后一行更改为:employ_list.append(new_employee)

我有一些建议。我将使用数据类来演示这些概念(参考:https://docs.python.org/3/library/dataclasses.html)。

  1. 为什么不拥有相同的类,但要有一个标志来指定您的人员是员工,例如:
from dataclasses import dataclass, asdict
@dataclass
class Person:  # <- name a better name
is_employee: bool = False
  1. 使用继承。这两个类都有很多重复的字段,因此继承在您的示例中应该可以完美地工作
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', ...)

最新更新