Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Create List of Object 's for object parameter

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading