繁体   English   中英

是否需要 deepcopy 从本地对象复制数据

[英]is deepcopy needed to copy data from local objects

如果我有这个应该怎么办

class ObjectA:
    def __init__(self):
        self.some_member = SomeComplexObject()

    def get_some_result(self):
        return self.some_member

然后这样做

a = ObjectA().get_some_result()

我尝试了几次,似乎工作正常,但我的期望是a应该保留垃圾,因为ObjectA是在本地创建的并且没有分配给任何变量。

我希望正确的方法应该是

a = copy.deepcopy(ObjectA().get_some_result())

我是否理解错误 python 的工作原理?

我认为您在帖子中遗漏了一些内容,您的代码会引发语法错误。

假设您编写了我认为正确的代码:

class ObjectA(object):
    def __init__(self):
        self.some_member = "some_value"

    def get_some_result(self):
        return self.some_member

if __name__ == "__main__":
    # This would create an instance of ObjectA in memory,
    # then call get_some_result() and assign the result (reference)
    # to the variable a
    a = ObjectA().get_some_result()

    # This will create a new ObjectA in memory
    # then call get_some_result() and assign the result (reference)
    # as a parameter of deepcopy.
    # in this case the constructor of the object assigns a fixed value,
    # so python just stores the string 'some value' as a const value in the memory
    # and the string object is actually always the same
    a = copy.deepcopy(ObjectA().get_some_result())

    # Example:
    obj1 = ObjectA()
    obj2 = ObjectA()

    print(id(obj1)) # 4561426512
    print(id(obj2)) # 4562720224
    print(id(ObjectA()) # 4594936224
    print(id(ObjectA()) # 4594869824

    print(id(obj1.get_some_result())) # 4562116656
    print(id(obj2.get_some_result())) # 4562116656
    

同样从文档中读取,似乎在某些情况下 deepcopy 只会返回引用而不创建新的 object。

来自: https://docs.python.org/3/library/copy.html因为深拷贝复制了它可能复制的所有内容,例如打算在副本之间共享的数据。

此外,字符串的行为如下(不可变):

>>> a = "strawberry"
>>> b = "strawberry"
>>> id(a) == id(b)
True
>>> a = "strawberry"
>>> b = "Strawberry"
>>> id(a) == id(b)
False

如果分配给成员的值是可变的 object,则情况不同。

暂无
暂无

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM