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

前端 未结 4 1701
终归单人心
终归单人心 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:33

    I think that looping over the fields probably is the easiest way. All the other options I can think of involve creating a new object.

    from dataclasses import fields
    
    marker_a = Marker(5)
    marker_b = Marker(0, 99)
    
    for field in fields(Marker):
        setattr(marker_b, field.name, getattr(marker_a, field.name))
    
    print(marker_b)  # Marker(a=5, b=1.0)
    

提交回复
热议问题