[英]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.