首页 > 解决方案 > Avoid class initialization modified in method in python

问题描述

My code is below:

import numpy as np

class xx():
   def __init__(self, x):
      self.x = x
   def main(self):
      for i in [0,1,2,3]:
         y = self.x
         y[0, i] = 0
         print(y)
z = np.array([[0.5,0.6,0.7,0.8],[1,2,3,4],[6,4,3,1]])        
xx(z).main()

My original code is far more complicated than this, so I decided to create a similar example on the issue.

I meant to only change y in the for loop, and reassign y with self.x. but it seemed that self.x was changed in the for loop too. How can I avoid self.x getting modified each time as y changes?

标签: pythonclassinitialization

解决方案


I would recommend using copy.deepcopy()

import copy

class xx():
   def __init__(self, x):
      self.x = x
   def main(self):
      for i in [0,1,2]:
         y = copy.deepcopy(self.x)
         y[0, i] = 0
         print(y)
z = np.array([[1,1,1],[2,2,2]])
xx(z).main()

>>>[[0 1 1]
    [2 2 2]]

>>>[[1 0 1]
    [2 2 2]]

>>>[[1 1 0]
    [2 2 2]]

推荐阅读