【发布时间】:2017-11-21 19:36:06
【问题描述】:
我试图使用下面的replace_object() 之类的成员函数将一个Python 对象分配给另一个就地。但是,如您所见,object_A 保持不变,复制object_B 的唯一方法是创建一个全新的对象object_C,这违背了就地分配的目的。
这里发生了什么,我该如何就地进行分配?
class some_class():
def __init__(self, attribute):
self.attribute = attribute
def replace_object(self, new_object):
self = new_object
# Does this line even have any effect?
self.attribute = new_object.attribute
self.new_attribute = 'triangle'
return self
object_A = some_class('yellow')
print(object_A.attribute) # yellow
object_B = some_class('green')
object_C = object_A.replace_object(object_B)
print(object_A.attribute) # yellow
print(object_C.attribute) # green
#print(object_A.new_attribute) # AttributeError!
print(object_B.new_attribute) # triangle
print(object_C.new_attribute) # triangle
我也尝试过使用copy.copy() 处理深层副本,但无济于事。
一个有趣的转折是,如果我替换
object_C = object_A.replace_object(object_B)
与
object_A = object_A.replace_object(object_B)
然后我得到我想要的。但是为什么replace_object()中的self = new_object语句不能达到同样的结果呢?
PS:我有一个很好的理由来做这个就地分配,所以虽然这可能不是一般的最佳实践,但在这里跟我一起去吧。
【问题讨论】:
-
这不是 Python 中赋值的工作方式,即使对于专家来说,尝试改变这些语言机制也不太可能顺利。 Here's a quick guide to what assignment actually does in Python.
-
你能解释一下为什么你认为你需要这样做吗?
-
@ScottHunter ...因为显而易见的替代方案,即
object_A = object_A.replace_object(object_B),似乎是多余的。 -
为什么不能只复制所有属性以镜像传入对象中的属性,或者您正在定义“平等”。
-
正如我已经解释的那样,那是因为你这样做了
self = new_object。不要那样做,因为现在当你这样做时:self.attribute = new_object.attribute该语句等同于new_object.attribute = new_object.attribute,即完全没有意义。
标签: python python-3.x oop