简体   繁体   中英

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

Simply, if I have base class:

@dataclass
class Base:
  foo: int
  bar: int

and derived 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 . 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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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