Python使用dataclass将基类对象转换为子类

Python使用dataclass将基类对象转换为子类,python,python-dataclasses,Python,Python Dataclasses,我有一个Employee基类和一个Manager子类。子类接受Employee obj并将其转换为Manager 下面的代码运行良好,但是我正在尝试确定如何使用dataclass创建相同的代码 class Employee: def __init__(self, id: int, name: str): self.id = id self.name = name class Manager(Employee): def __init__(self

我有一个Employee基类和一个Manager子类。子类接受Employee obj并将其转换为Manager

下面的代码运行良好,但是我正在尝试确定如何使用dataclass创建相同的代码

class Employee:
    def __init__(self, id: int, name: str):
        self.id = id
        self.name = name

class Manager(Employee):
    def __init__(self, employee: Employee, region: str):
        super().__init__(**vars(employee))
        self.region = region

e1 = Employee(1, 'Bob')
e2 = Employee(2, 'Sally')

# Sally gets promoted to manager of southwest region
e2 = Manager(e2, 'southwest')
这是我到目前为止所拥有的,我不确定如何传递所有必需的参数

@dataclass
class Employee:
    id: int
    name: str

@dataclass
class Manager(Employee):
    region: str
    def __new__(cls, employee: Employee, region: str):
        obj = object.__new__(cls)
        super().__init__(obj, **vars(employee))
        return obj

e2 = Employee(2, 'Sally')
>>经理(e2地区,西南地区)
回溯(最近一次呼叫最后一次):
文件“”,第1行,在
TypeError:\uuuu init\uuuu()缺少1个必需的位置参数:“name”

我不确定所有的
\uuuuu new\uuuuu
元类hackery都要完成什么,但是您很少需要在Python中重写
\uuuuuuuuuu new\uuuu
,这也不例外

@dataclass
class Employee:
    id: int
    name: str

@dataclass
class Manager(Employee):
    region: str

e2 = Employee(2, 'Sally')
m2 = Manager(2, 'Sally', 'southwest')
数据类就是这样;用于存储数据的类。数据类继承的工作方式与您预期的一样。只要继承就行了

如果您仍然希望将
员工
作为参数,则可以使用
\uuuuu init\uuuuu
而不是
\uu new\uuuuuu

@dataclass
class Employee:
    id: int
    name: str

@dataclass
class Manager(Employee):
    region: str
    def __init__(self, employee: Employee, region: str):
        super().__init__(**vars(employee))
        self.region = region

理想情况下,我希望将e2 obj传递给Manager类,并分配属性,而不必指定每个属性。尤其是在员工拥有数百个属性的情况下。我尝试使用
\uuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuu
因为它在
\uuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuu。在我看来,
\uuuu init\uuu
仍然可以正常工作。如果这对你不起作用,请随时澄清,我们可以再看一看。
@dataclass
class Employee:
    id: int
    name: str

@dataclass
class Manager(Employee):
    region: str
    def __init__(self, employee: Employee, region: str):
        super().__init__(**vars(employee))
        self.region = region