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

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

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

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


        
4条回答
  •  Happy的楠姐
    2020-12-21 01:27

    @dataclass
    class Marker:
        a: float
        b: float = 1.0
    
    marker_a = Marker(0.5)
    
    marker_b = Marker(**m1.__dict__)
    
    marker_b
    
    # Marker(a=0.5, b=1.0)
    

    If you didn't want to create a new instance, try this:

    marker_a = Marker(1.0, 2.0)
    marker_b = Marker(11.0, 12.0)
    
    marker_b.__dict__ = marker_a.__dict__.copy()
    
    # result: Marker(a=1.0, b=2.0)
    

    Not sure whether that's considered a bad hack though...

提交回复
热议问题