0

I have written a simplified version of my code with this problem (Python 3.9):

class myClass:
    def __init__(self, elements: list):
        for el in elements:
            self.addElement(el)

    def addElement(self, element):
        self.classElements.append(element)

    classElements = []


First = myClass(['el1', 'el2'])
Second = myClass(['el3', 'el4'])

print("Elements in first instance: {0}".format(First.classElements))
print("Elements in second instance: {0}".format(Second.classElements))

Here is the console output:

Elements in first instance: ['el1', 'el2', 'el3', 'el4']
Elements in second instance: ['el1', 'el2', 'el3', 'el4']

However after my logic it should be like this:

Elements in first instance: ['el1', 'el2']
Elements in second instance: ['el3', 'el4']

Why does First contain the elements of Second and vice versa even though both objects have nothing to do with eachother except for being the same class?

jonrsharpe
  • 115,751
  • 26
  • 228
  • 437
EVARATE
  • 115
  • 1
  • 1
  • 9
  • It fixes my problem but I don't understand why this happens in the first place. Does my version somehow redefine definition of `myClass` when constructing `First`? – EVARATE Dec 08 '20 at 20:53
  • 1
    Note that various answers also explain exactly *why* this happens. – jonrsharpe Dec 08 '20 at 20:54

0 Answers0