Python中创建含TestB列表的TestA对象,为何两个实例列表值相同?
问题原因
你定义的testBlist是类属性,它属于testA类本身而非类的实例。所有testA的实例都会共享这同一个列表对象,不管通过a.testBlist还是b.testBlist操作的都是同一个列表。所以当你分别向两个实例的列表添加元素时,实际上是在给同一个列表添加元素,最终两个实例的列表自然完全相同,print结果为True。
解决方法
把testBlist改为实例属性,在__init__方法中初始化,让每个testA实例拥有独立的列表:
class testA: def __init__(self, n) -> None: self.name = n self.testBlist = [] # 在这里初始化实例属性 class testB: def __init__(self, n) -> None: self.name = n a = testA("test1") b = testA("test2") a.testBlist.append(testB("testB1")) b.testBlist.append(testB("testB2")) print(a.testBlist == b.testBlist ) # 此时结果为False
这样修改后,每个testA实例的testBlist都是独立的列表,各自添加元素后内容不同,比较结果就会是False。
内容的提问来源于stack exchange,提问作者Dreamenemy
相关产品推荐
相关产品推荐

