python - Adding classes, preventing changing indexes from affecting data -


i have class k() has __add__() method works follows

d_1 = k(dict(a=3, b=5), dict(b=45,c=23)) d_2 = k(dict(a='three',b='two'), dict(b='wa',c='wo')) >>d = d_1 + d_2 >>d == k({'a': 3, 'b': 5}, {'b': 45, 'c': 23}, {'a': 'three', 'b': 'two'}, {'b': 'wa', 'c': 'wo'}) true 

however, if change data

d_1['c'] = 'apples' d_2['c'] = 'oranges' 

and check again...

>>d == k({'a': 3, 'b': 5}, {'b': 45, 'c': 23}, {'a': 'three', 'b': 'two'}, {'b': 'wa', 'c': 'wo'}) false 

the changing data has affected original addition method. i've tried using .copy() create copies of variables we're adding, , use those- haven't had luck...

def __add__(self, other):     scopy, ocopy = self.copy(),other.copy()     slist,olist = [],[]     x in scopy.list_of_dictionaries_from_init:         self_temp.append(x)     in other_copy.list_of_dictionaries_from_init:          temp.append(i)     return k(*(self_copy.list_of_dictionaries_from_init + olist)) 

this outright doesn't work

i'm not sure how make work copies

the problem here copy method presumably making new list same dicts. when copy collection elements mutable collections, don't copied.

if want copy "all way down", use deepcopy function. example, can change own copy method call deepcopy. (and __init__ method well.)

for example, maybe this:

def copy(self):     return k(copy.deepcopy(self.list_of_dictionaries_from_init)) 

meanwhile, add method doesn't make sense. create slist , olist lists, try append self_temp , temp lists, , try use self_temp if k instance instead of list. if you've got copy method, may simpler first define __iadd__, , define __add__ in terms of it:

def __iadd__(self, other):     self.list_of_dictionaries_from_init += other.list_of_dictionaries_from_init  def __add__(self, other):     self_copy = self.copy()     self_copy += other     return self_copy 

Comments

Popular posts from this blog

java - Spring Data JPA: Why findOne(id) executing delete query internally? -

python - Mongodb How to add addtional information when aggregating? -

java - Incorrect order of records in M-M relationship in hibernate -