Create List of Object 's for object parameter

Question:

im trying to create an Object name "TestA", TestA will has list of TestB object. When i create two object TestA and push deiffrent TestB’ to their list they has 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

Asked By: Dreamenemy

||

Answers:

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
Answered By: John3331

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 )
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.