python - Method changes all instances of class inside list -
in script have these classes:
class action: def __init__(self,ac_type,ac_date): self.ac_type = ac_type self.ac_date = ac_date class user: actions = [] def __init__(self,i_id): self.ivi_id = i_id def add(self,act): self.actions.append(act) def get_len(self): return len(self.actions)
i want create list of "user" elements , add of theme actions. in following way:
for in range(len(data_queue)): ind = users_id.index(data_queue[i].i_id); act = action(0,data_queue[i].added) users[ind].add(act)
but after running see every action data_queue added every user users. wrong! shall change?
the code using class attribute shared instances of class , class itself.
use instance attribute instead:
class user: def __init__(self,i_id): self.ivi_id = i_id self.actions = [] def add(self,act): self.actions.append(act) def get_len(self): return len(self.actions)
btw, code using index iterate sequence data_queue
. iterate sequence unless need index.
for queue in data_queue: ind = users_id.index(queue.i_id) act = action(0, queue.added) users[ind].add(act)
Comments
Post a Comment