如何从超类的实例中正确继承data?例如,考虑一些我可以开始工作,但其行为令人困惑的事情:
from dataclasses import dataclass
from typing import Self
@dataclass
class SuperClass:
hello: int
world: int
@dataclass
class ChildClass(SuperClass):
kitty: int
@classmethod
def from_super(cls, s: SuperClass, kitty: int) -> Self:
x = cls(s, kitty=kitty)
return x
现在,让我们看看这是否有效:
super_instance = SuperClass(0, 1)
child = ChildClass.from_super(super_instance, 2)
child
这会产生输出:
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
Cell In[48], line 1
----> 1 ChildClass.from_super(super_instance, 2)
Cell In[46], line 15
13 @classmethod
14 def from_super(cls, s: SuperClass, kitty: int) -> Self:
---> 15 x = cls(s, kitty=kitty)
16 return x
TypeError: ChildClass.__init__() missing 1 required positional argument: 'world'
那么我如何正确地做到这一点,而不需要手动写出超类中的每个变量实例化?
在您的示例中,您似乎试图将数据从超类 (
SuperClass
) 的实例继承到子类 (ChildClass
)。但是,您的方法存在一些问题,主要是由于 dataclass
装饰器和继承在 Python 中的工作方式所致。
要从超类的实例化中正确继承数据,您需要使用继承。让我们修改您的代码以演示使用继承执行此操作的正确方法:
ChildClass
继承自 SuperClass
。super()
函数初始化超类部分。from dataclasses import dataclass
from typing import Self
@dataclass
class SuperClass:
hello: int
world: int
@dataclass
class ChildClass(SuperClass):
kitty: int
@classmethod
def from_super_wtf(cls, s: SuperClass, kitty: int) -> Self:
x = cls(hello=s.hello, world=s.world, kitty=kitty)
return x
@classmethod
def from_super_works(cls, s: SuperClass, kitty: int) -> Self:
x = cls(hello=s.hello, world=s.world, kitty=kitty)
return x
@classmethod
def from_super_sane(cls, s: SuperClass, kitty: int) -> Self:
x = cls(hello=s.hello, world=s.world, kitty=kitty)
return x
# Testing the code
super_instance = SuperClass(0, 1)
child = ChildClass.from_super_works(super_instance, 2)
child_wtf = ChildClass.from_super_wtf(super_instance, 2)
child_sane = ChildClass.from_super_sane(super_instance, 2)
print(child) # Expected: ChildClass(hello=0, world=1, kitty=2)
print(child_wtf) # Expected: ChildClass(hello=0, world=1, kitty=2)
print(child_sane) # Expected: ChildClass(hello=0, world=1, kitty=2)
在此方法中,
ChildClass
继承自SuperClass
,这意味着它还继承了hello
和world
属性。创建新实例时