首页 > 解决方案 > 如何在类方法中生成新实例?

问题描述

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

标签: pythonpython-3.x

解决方案


我有几个建议给你。我将使用数据类来演示这些概念(参考: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', ...)

推荐阅读