0

I'm trying to create an object named "TestA", which will have a list of "TestB" objects. When I create two "TestA" objects and push different "TestB" objects to their lists, they end up having the same value.

class testA:
    testBlist = []
    def __init__(self, n) -> None:
        self.name = n
        pass

class testB:
    def __init__(self, n) -> None:
        self.name = n
        pass

a = testA("test1")
b = testA("test2")


a.testBlist.append(testB("testB1"))
b.testBlist.append(testB("testB2"))

print(a.testBlist == b.testBlist )

#result is True

Dreamenemy
  • 95
  • 1
  • 9
  • 1
    class testA only has one list per class, so you are appending to the same list i.e. `testA.testBlist `. – DarrylG Oct 03 '22 at 13:20
  • 1
    Also [In python how is a mutable class attribute treated](https://stackoverflow.com/q/30138430/4046632) – buran Oct 03 '22 at 13:23
  • 2
    As a side note, the `pass` statement is your `__init__` methods is redundant, just remove it. – buran Oct 03 '22 at 13:25

2 Answers2

2

This is because testBlist is a class attribute and is shared among all instances of testA. You want testBlist to be an attribute of an instance. So like this

class testA:
    
    def __init__(self, n) -> None:
        self.name = n
        self.testBlist = []

class testB:
    def __init__(self, n) -> None:
        self.name = n
        pass

a = testA("test1")
b = testA("test2")


a.testBlist.append(testB("testB1"))
b.testBlist.append(testB("testB2"))


print(a.testBlist == b.testBlist )
print(a.testBlist[0].name)
print(b.testBlist[0].name)

Output

False
testB1
testB2
John3331
  • 46
  • 3
0

testBlist =[], is static variable in class testA and also mutable. even you instantiate the class two times, the object will have same value, because the refrence to same variable/object list. that is why they always has same value. try this if this is the one you expected:

class testA:
    # testBlist = []
    def __init__(self, n) -> None:
        self.name = n
        self.testBlist = [n]

class testB:
    def __init__(self, n) -> None:
        self.name = n
        pass

a = testA("test1")
b = testA("test2")


a.testBlist.append(testB("testB1"))
b.testBlist.append(testB("testB2"))
a.testBlist.append(testB("testB3"))

print(a.testBlist)
print (b.testBlist)

print(a.testBlist == b.testBlist )