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
... and so on.
…等等。
2 个解决方案
#1
15
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!
如果您经常这样做,那么在“实用程序”模块中使用这段代码一次绝对是您的胜利!
#2
3
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. Objects shouldn't morph from one object to another, similar but separate object, very often at all.
如果它们是相似的,并且需要更改状态,那么听起来您确实拥有一个类的实例,以及一个模式或相似的属性来确定它的行为。物体不应该从一个物体变成另一个物体,类似但又独立的物体。
#1
15
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!
如果您经常这样做,那么在“实用程序”模块中使用这段代码一次绝对是您的胜利!
#2
3
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. Objects shouldn't morph from one object to another, similar but separate object, very often at all.
如果它们是相似的,并且需要更改状态,那么听起来您确实拥有一个类的实例,以及一个模式或相似的属性来确定它的行为。物体不应该从一个物体变成另一个物体,类似但又独立的物体。