Copy of a class object with a numpy array as property

huangapple go评论74阅读模式
英文:

Copy of a class object with a numpy array as property

问题

以下是您提供的代码的翻译:

import numpy as np
import copy as cp

class Test():
    x = 5
    arr = np.array([5, 3])

TEST_1 = Test()
TEST_2 = cp.copy(TEST_1)

如果我改变TEST_1的x值,它不会影响TEST_2:

print(TEST_2.x)
TEST_1.x += 1
print(TEST_2.x)

>>> 5

>>> 5

但是,如果我尝试更改TEST_1的数组,它也会更改TEST_2的数组:

print(TEST_2.arr)
TEST_1.arr += np.array([1, 1])
print(TEST_2.arr)

>>> [5 3]

>>> [6 4]

我知道这是因为我需要创建数组的副本,但我不知道如何告诉Python在类内部的数组上执行此操作。

希望这能帮助您理解代码的翻译部分。

英文:

I have a class where I defined a numpy array and then I created a copy of an object of that class:

import numpy as np
import copy as cp

class Test():
    x=5
    arr=np.array([5,3])

TEST_1=Test()
TEST_2=cp.copy(TEST_1)

If I change the value of x for TEST_1 it's ok, it doesn't affect TEST_2:

print(TEST_2.x)
TEST_1.x+=1
print(TEST_2.x)

>>>5

>>>5

But if I try to change the array of TEST_1 it also changes the array of TEST_2:

print(TEST_2.arr)
TEST_1.arr+=np.array([1,1])
print(TEST_2.arr)

>>>[5 3]

>>>[6 4]

I know it's because I have to create a copy of the array, but I don't know how to tell Python to do it when the array it's inside a class.

Thank you and sorry for the bad English.

答案1

得分: 1

好的,我成功解决了,我这样做:

class Test():
    def __init__(self):
        self.arr = np.array([5, 3])
        self.x = 5

    def __deepcopy__(self, memo):
        cls = self.__class__
        result = cls.__new__(cls)
        memo[id(self)] = result
        for k, v in self.__dict__.items():
            setattr(result, k, cp.deepcopy(v, memo))
        return result

现在复制的数组不会改变。

英文:

Ok I managed to solve it, I do this:

class Test():
def __init__(self):
    self.arr=np.array([5,3])
    self.x=5
    
def __deepcopy__(self, memo):
    cls = self.__class__
    result = cls.__new__(cls)
    memo[id(self)] = result
    for k, v in self.__dict__.items():
        setattr(result, k, cp.deepcopy(v, memo))
    return result

And now the array of the copy doesn't change

huangapple
  • 本文由 发表于 2023年5月13日 18:21:19
  • 转载请务必保留本文链接:https://go.coder-hub.com/76242226.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定