0

I have this two classes, that come from one common abstract class that will be the father:

class AbstractClass(object):
    data_table = ''
    data = []
    def __init__(self, id, array):
         self.getFromId(id)
         self.data += array

    def getFromId(self, id):
        #Get data from the 'data_table' and init its values
        ...



class ParentClass(AbstractClass):
    data_table = 'table_parent'

    def __init__(self, id, array):
         super(ParentClass, self).__init__(id, array)



class ChildClass(AbstractClass):
    data_table = 'table_child'

    def __init__(self, id, array):             
         super(ChildClass, self).__init__(id, array)

    def getParent(self):
         return parentObject = ParentClass(id, ['e', 'f', 'g'])

The problem is that when i call child.getParent(), in the object child, the element array are being writed by the parent. For example, we have this call:

>>> child = ChildClass('1234', ['a', 'b', 'c'])
>>> print(child.data) 
['a', 'b', 'c']

>>> child.getParent()
>>> print(child.data) 
['a', 'b', 'c', 'e', 'f', 'g']

But the parent musnt modify the values of the child. I dont know why this is happening. It can be because they have the same inheritance class, or the same method names? It doesnt have sense, since they are different objects with different instantiation...

megavexus
  • 131
  • 4

1 Answers1

0

Like @Rawing said in the comments, it is answered in How do I avoid having class data shared among instances?

The problem was that i wasnt initializing the data variable in the init definition. The fix is simple:

class AbstractClass(object):
    data_table = ''

    def __init__(self, id, array):
         self.getFromId(id)
         self.data = [] # We have to initialize the variable in the init and not in the class
         self.data += array

(Yes, i know that the data = [] and data += array doesnt have sense, but is a simplification of the real problem, so i will keep as it is written :P)

Thanks!!

megavexus
  • 131
  • 4