0

I have a code that creates an object inside a loop. The object has a list that contains different type of object.

class A:
    a = ''
    def __init__(self):
        pass

class B:
    def __init__(self):
        pass
    list_of_A = list()

for i in range(3):
    _b = B()
    for j in range(2):
        _a = A()
        _b.list_of_A.append(_a)
    print(len(_b.list_of_A))

The output is: 2 4 6

What I expected was: 2 2 2

I tried deleting _b at the end of the inner loop. But didn't work. How should I make sure the loop creates a new object of B.

1
  • 1
    Move list_of_A = list() into __init__ and prepend self., i.e. def __init__(self): self.list_of_A = list(). BTW, list() can be []. Commented Dec 1, 2019 at 5:30

2 Answers 2

1

One way is to make list_of_A an instance variable, so it creates new list everytime you create an object:

class B:
    def __init__(self):
        self.list_of_A = list()   # or = []

When you have the following arrangement:

class B:
    def __init__(self):
        pass
    list_of_A = list()

list_of_A is shared by all objects of that class (because this is a class variable), and so you are appending to the same list object.

Sign up to request clarification or add additional context in comments.

Comments

1

Do this:

class B:
    def __init__(self):
        self.list_of_A = list()

Reason: Class Variable(or Static Variable) vs Instance Variable

In your code, list_of_A is a class variable(or static variable) so it is same for all the objects(or instances) of class B. In the code suggested above, list_of_A is an instance variable so it is different and unique for each object(or instance) of class B.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.