Easiest way to copy all fields from one dataclass instance to another?

前端 未结 4 1710
终归单人心
终归单人心 2020-12-21 00:58

Let\'s assume you have defined a Python dataclass:

@dataclass
class Marker:
    a: float
    b: float = 1.0
         


        
4条回答
  •  北荒
    北荒 (楼主)
    2020-12-21 01:26

    The dataclasses.replace function returns a new copy of the object. Without passing in any changes, it will return a copy with no modification:

    >>> import dataclasses
    >>> @dataclasses.dataclass
    ... class Dummy:
    ...     foo: int
    ...     bar: int
    ... 
    >>> dummy = Dummy(1, 2)
    >>> dummy_copy = dataclasses.replace(dummy)
    >>> dummy_copy.foo = 5
    >>> dummy
    Dummy(foo=1, bar=2)
    >>> dummy_copy
    Dummy(foo=5, bar=2)
    

    Note that this is a shallow copy.

提交回复
热议问题