gpt4 book ai didi

python - 将 (OOP) 对象分配给另一个对象

转载 作者:太空宇宙 更新时间:2023-11-04 04:54:21 27 4
gpt4 key购买 nike

我试图使用成员函数(例如下面的 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:我有一个很好的理由来做这个就地作业,所以虽然这可能不是一般的最佳实践,但请跟着我一起来。

最佳答案

您不能“将一个对象分配给另一个对象”。您可以将新的和现有的对象分配给新的和现有的名称。

self = new_object 只是说“从现在开始,名称 self 将引用 new_object”,对旧对象不做任何事情。 (注意 self 只是一个变量名,与其他任何变量名一样,并且仅按照惯例指代类定义中的对象。)

后续命令 self.attribute = new_object.attribute 没有效果,因为 self 已经成为 new_object 的重复标签。

您可以将新对象的所有属性复制到旧对象。您最终会得到两个具有不同名称和相同属性的不同对象。相等性测试 (a == b) 将返回 false,除非你 overrode the equality operator对于这些对象。

要内联复制所有属性,您可以执行类似 this 的操作:

def replace_object(self, new_object):
self.__dict__ = new_object.__dict__.copy() # just a shallow copy of the attributes

很可能有更好的方法来做您想做的任何事情。

关于python - 将 (OOP) 对象分配给另一个对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47421289/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com