我有以下代码:
class PWA_Parse():
include = []
def appendInclude(self, element):
self.include.append(element)
def printMemory(self):
print "Class location", hex(id(self)), "List location:", hex(id(self.include))
a = PWA_Parse()
b = PWA_Parse()
a.appendInclude(5)
a.printMemory()
b.printMemory()
两者的列表内存地址相同:
Class location 0x29e9788 List location: 0x29e95d0
Class location 0x29e97b0 List location: 0x29e95d0
如何在类定义中创建一个列表,以便在实例化时获得两个单独的列表? (提示:我已经用list()试过了)
通过将
include
声明为类变量,可以使该类的所有实例共享同一个变量include
相反,您应该通过在
__init__()
方法中初始化include
使其成为一个实例变量:在
__init__
方法中创建一个新列表,实例化后自动调用该列表相关问题 更多 >
编程相关推荐