In Python(2.7), I want to modify some of instance variables by using the instance method. For efficient coding, I tried to make a list of class variables and use for loop to assign a new value to each variable. I made an instance and ran a method but instance variables did not change. Here's the code for example.
import numpy as np
class myclass:
def __init__(self):
self.A = np.array([1,2,3])
self.B = np.array([4,5,6])
self.C = np.array([7,8,9])
def addx(self, x): #value assigning via this method
V = [self.A, self.B, self.C]
for v in V:
print(id(v))
v = np.hstack([v,x]) # <<-- here
print(id(v))
print('(step1)')
ins = myclass()
print(ins.A)
print(id(ins.A))
print('\n(step2)')
ins.addx(1) #value assigning in this line
print(ins.A)
print(id(ins.A))
the result (with some comments):
(step1)
[1 2 3]
47985418888576 <- (id of ins.A)
(step2)
47985418888576 <- (id of ins.A)
47985628039168 <- (assigning step for ins.A)
47985418888896
47985628039088
47985624314064
47985628039168
[1 2 3]
47985418888576 <- (id of ins.A)
the desired result for the (step2) is
[1 2 3 1]
How can I get this result using list and for loop? Or using any other efficient way, not a repeated codes for each variables?
Additionally, i checked the id of variables. We can see that the variables in list has same id with class variables. But in the assigning step, it has a different id.
Comments
Post a Comment