0

I am new to Python and I am trying to use a function to add elements to an object owned list. Here is a simplified version of my code:

class TElement:
    vec = []

class GTop:

    ElList = []

    def AddElement(self, vect):
        NewEl = TElement() 
        for i in range(len(vect)): 
            NewEl.vec.append(vect[i])

        self.ElList.append(NewEl)


myvec1 = ["a",1,2,"b"]
myvec2 = ["a","c",2,"b"]

Mytop = GTop()

Mytop.AddElement(myvec1)

Mytop.AddElement(myvec2)

With the above code I get:

Mytop.ElList[0].vec = ['a', 1, 2, 'b']

Mytop.ElList[1].vec = ['a', 1, 2, 'b', 'a', 'c', 2, 'b']

While I wanted:

Mytop.ElList[0].vec = ['a', 1, 2, 'b']

Mytop.ElList[1].vec = ['a', 'c', 2, 'b']

For some reason, when I exit the AddElement function NewEl is not being deleted. Could you clarify what I am doing wrong? Thanks.

user1477337
  • 385
  • 2
  • 9

1 Answers1

2

If you change TElement like this you should get the output you expected:

class TElement:
    def __init__(self):
        self.vec = []

As @delnan pointed out in a comment, read the other answer, it explains well.

Why do attribute references act like this with Python inheritance?

Community
  • 1
  • 1
janos
  • 120,954
  • 29
  • 226
  • 236