将所有字段从一个Python数据类实例复制到另一实例的最简单方法 [英] Easiest way to copy all fields from one Python dataclass instance to another instance

查看:93
本文介绍了将所有字段从一个Python数据类实例复制到另一实例的最简单方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设您已经定义了Python数据类:

Let's assume you have defined a Python dataclass:

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

将值从实例marker_a复制到另一个实例marker_b的最简单方法是什么?

What's the easiest way to copy the values from an instance marker_a to another instance marker_b?

这是我尝试实现的示例:

Here's an example of what I try to achieve:

marker_a = Marker(1.0, 2.0)
marker_b = Marker(11.0, 12.0)
# now some magic happens which you hopefully can fill in
print(marker_b)
# result: Marker(a=1.0, b=2.0)

作为边界条件,我不想创建新实例并将其分配给marker_b.好的,我可以遍历所有定义的字段,然后逐个复制值,但是我想必须有一种更简单的方法.

As a boundary condition, I don't want to create and assign a new instance to marker_b. Ok, I could loop through all defined fields and copy the values one by one, but there has to be a simpler way, I guess.

推荐答案

我认为循环这些字段可能是最简单的方法.我能想到的所有其他选项都涉及创建一个新对象.

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)

这篇关于将所有字段从一个Python数据类实例复制到另一实例的最简单方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆