![](/img/trans.png)
[英]How to create new instance of current class inside the current class method?
[英]How do I generate a new instance inside of a class method?
我為我的文字冒險游戲創建了一個 class,玩家可以在其中聘請申請人。 但是一旦他們雇用了申請人,那個人就會成為雇員。 因此,我希望該申請人實例成為我的Employee
class 的實例。 有沒有辦法做到這一點或更好的方法?
這是我的申請人 class:
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
class 中自動為申請人創建一個新實例。
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:
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)
您可能還不想 append 申請人記錄,但將最后一行更改為: employ_list.append(new_employee)
我有幾個建議給你。 我將使用數據類來演示這些概念(參考: 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', ...)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.