Python-将对象的属性复制到另一个对象的正确方法是什么? [英] Python - what is the correct way to copy an object's attributes over to another?

查看:179
本文介绍了Python-将对象的属性复制到另一个对象的正确方法是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两节课。除了2个属性外,它们几乎相同。我需要将所有属性从一个属性复制到另一个属性,我只是想知道是否存在某种模式或最佳做法,还是我是否应该基本上:

I have two classes. They're almost identical, except for 2 attributes. I need to copy all the attributes over from one to the other, and I'm just wondering if there is a pattern or best practice, or if I should just basically do:

spam.attribute_one = foo.attribute_one
spam.attribute_two = foo.attribute_two

...等等。

推荐答案

您提供的代码是正确且安全的,避免了意外绑定应该绑定的属性。但是,如果您偏爱自动化而不是安全性和正确性,则可以使用之类的东西:

The code you give is correct and safe, avoiding "accidentally" binding attributes that should not be bound. If you favor automation over safety and correctness, though, you could use something like...:

def blindcopy(objfrom, objto):
    for n, v in inspect.getmembers(objfrom):
        setattr(objto, n, v);

但是,我不建议这样做(由于第一段所隐含的原因;-)。 OTOH,如果您知道要复制的属性的名称,则可以使用以下命令:

However, I would not recommend it (for the reasons implied by the first para;-). OTOH, if you know the names of the attributes you want to copy, the following is just fine:

def copysome(objfrom, objto, names):
    for n in names:
        if hasattr(objfrom, n):
            v = getattr(objfrom, n)
            setattr(objto, n, v);

如果您经常执行此类操作,请在此代码中一次 实用程序模块对您来说绝对是一个胜利!

If you do this kind of thing often, having this code once in a "utilities" module can be a definite win for you!

这篇关于Python-将对象的属性复制到另一个对象的正确方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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