简体   繁体   English

Python - 将对象的属性复制到另一个的正确方法是什么?

[英]Python - what is the correct way to copy an object's attributes over to another?

I have two classes.我有两节课。 They're almost identical, except for 2 attributes.它们几乎相同,除了 2 个属性。 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

... and so on. ……等等。

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);

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: OTOH,如果您知道要复制的属性的名称,则以下内容就可以了:

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!如果你经常做这种事情,在“实用程序”模块中使用一次这段代码对你来说绝对是一个胜利!

If they're that similar, and need to change state, it sounds like you really have instances of one class, and a mode or similar attribute that determines how it behaves.如果它们非常相似,并且需要更改状态,那么听起来您确实拥有一个类的实例,以及一个决定其行为mode或类似属性。 Objects shouldn't morph from one object to another, similar but separate object, very often at all.对象不应该经常从一个对象变形到另一个类似但独立的对象。

I used dictionary comprehension to iterate through the items and call setattr() for another object.我使用字典理解来遍历项目并为另一个对象调用setattr()

{k: setattr(object_to, k, v) for k, v in object_from.dict().items()}

Since I don't need any new dict , I have not assigned the return value to any variable.由于我不需要任何新的dict ,因此我没有将返回值分配给任何变量。

Another way I tried is by using map()我尝试的另一种方法是使用 map()

dict(
    map(lambda item: (item[0], setattr(object_to, item[0], item[1])
                      ),
        object_from.dict().items()
        )
)

This might save a lot of loop iteration time.这可能会节省大量循环迭代时间。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 在条件语句中检查对象类型的正确方法是什么-Python - What is the correct way to check an object's type in a conditional statement - python 在Python中迭代实例对象的属性 - iterate over an instance object's attributes in Python 在Python中通过网络发送对象的最佳方法是什么? - What's the best way to send an object over a network in Python? Python - 复制 class object A 的正确方法是什么,其中包含一个 class 对象数组 B - Python - What is correct way to copy a class object A which contains an array of class objects B 在python中使用dict理解来遍历列表并制作字典的正确方法是什么? - What's the correct way to loop over a list and make a dictionary with dict comprehension in python? 在python中,一般来说,“对象的属性”是什么? - What are an 'object's attributes' in python and in general? 导入python包的正确方法是什么? - What's the correct way to import a python package? 如何将一个Python对象的所有属性复制到另一个? - How to copy all attributes of one Python object to another? 将类型信息添加到对象属性的pythonic方法是什么? - What is the pythonic way to add type information to an object's attributes? 在Python中将对象属性传递给函数的最优选方法是什么? - What is the most preferred way to pass object attributes to a function in Python?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM