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
>Solution :
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