简体   繁体   English

我可以使用其基础 class 的实例来初始化派生数据类吗?

[英]Can I init a derived dataclass using an instance of its base class?

Simply, if I have base class:简单地说,如果我有基础 class:

@dataclass
class Base:
  foo: int
  bar: int

and derived class:并派生出 class:

@dataclass
class Derived(Base):
  baz: int

I want to do this:我想做这个:

base = Base(1, 2)
derived = Derived(base, 3)

But this would try to assign base to derived.foo .但这会尝试将base分配给derived.foo Is there a way to accomplish this in such a way that I don't have to iterate over each field?有没有一种方法可以让我不必遍历每个字段? I could for example serialize base to json, add the additional field, then deserialize to derived but that seems a bit hacky.例如,我可以将base序列化为 json,添加附加字段,然后反序列化为derived ,但这似乎有点 hacky。

You can unpack the fields of one instance when creating another:您可以在创建另一个实例时解压缩一个实例的字段:

>>> from dataclasses import asdict
>>> Derived(**asdict(base), baz=3)  # by keyword
Derived(foo=1, bar=2, baz=3)
>>> Derived(*asdict(base).values(), 3)  # positional
Derived(foo=1, bar=2, baz=3)

Note that using asdict makes a deep-copy, so that there won't be any references accidentally shared.请注意,使用asdict会进行深层复制,这样就不会意外共享任何引用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM