0

I have two python classes A and B. Class B takes class A as an input variable. The reason I do this instead of making A a parent class of B is that A is very cpu-consuming in my case (the code below is just a simplified example). Therefore I always save class A as a pickle file so that I can reuse it. In class A, a list of dictionaries my_list is saved as an attribute. Then in class B it copies A().my_list to B().my_new_list and adds two new key-value pairs. The simplified code is shown below:

import random

class A(object):
    def __init__(self):
        self.make_list()
    def make_list(self):
        self.my_list = [{'a':1, 'b':2, 'c':3}, {'a':4, 'b':5, 'c':6}]

class B(object):
    def __init__(self, classA):
        self.my_new_list = classA.my_list.copy()
        self.make_new_list()
    def make_new_list(self):
        for d in self.my_new_list:
            d['d'] = random.randrange(10)
            d['e'] = random.randrange(10)

The weird thing happens when I call class B multiple times with the same input class A. For example, if I call it 5 times:

clsA = A() 
for _ in range(5):
    print(clsA.my_list) # I expect clsA.my_list to always be [{'a':1, 'b':2, 'c':3}, {'a':4, 'b':5, 'c':6}]
    print(B(classA=clsA).my_new_list)

I get the following output:

[{'a': 1, 'b': 2, 'c': 3}, {'a': 4, 'b': 5, 'c': 6}]
[{'a': 1, 'b': 2, 'c': 3, 'd': 2, 'e': 7}, {'a': 4, 'b': 5, 'c': 6, 'd': 6, 'e': 3}]
[{'a': 1, 'b': 2, 'c': 3, 'd': 2, 'e': 7}, {'a': 4, 'b': 5, 'c': 6, 'd': 6, 'e': 3}]
[{'a': 1, 'b': 2, 'c': 3, 'd': 0, 'e': 5}, {'a': 4, 'b': 5, 'c': 6, 'd': 2, 'e': 6}]
[{'a': 1, 'b': 2, 'c': 3, 'd': 0, 'e': 5}, {'a': 4, 'b': 5, 'c': 6, 'd': 2, 'e': 6}]
[{'a': 1, 'b': 2, 'c': 3, 'd': 5, 'e': 5}, {'a': 4, 'b': 5, 'c': 6, 'd': 5, 'e': 8}]
[{'a': 1, 'b': 2, 'c': 3, 'd': 5, 'e': 5}, {'a': 4, 'b': 5, 'c': 6, 'd': 5, 'e': 8}]
[{'a': 1, 'b': 2, 'c': 3, 'd': 4, 'e': 5}, {'a': 4, 'b': 5, 'c': 6, 'd': 5, 'e': 7}]
[{'a': 1, 'b': 2, 'c': 3, 'd': 4, 'e': 5}, {'a': 4, 'b': 5, 'c': 6, 'd': 5, 'e': 7}]
[{'a': 1, 'b': 2, 'c': 3, 'd': 9, 'e': 2}, {'a': 4, 'b': 5, 'c': 6, 'd': 6, 'e': 3}]

Obviously, something very unexpected happened: class B somehow someway changes the input class A after the first call. I expect the A class to be invariant so that I can reuse the same class A multiple times, which will save me a lot of cpu time. Anyone knows the reason for this unexpected inheritance, and how to change my code? Note that I don't want to make B a child class of A.

Shaun Han
  • 2,676
  • 2
  • 9
  • 29

0 Answers0