类的两个不同实例化在内存中的相同列表地址

2024-09-29 01:24:24 发布

您现在位置:Python中文网/ 问答频道 /正文

我有以下代码:

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()试过了)


Tags: 代码selfid列表includeparsedeflocation
2条回答

通过将include声明为类变量,可以使该类的所有实例共享同一个变量include

相反,您应该通过在__init__()方法中初始化include使其成为一个实例变量:

class PWA_Parse():
    def __init__(self):
        self.include = []

__init__方法中创建一个新列表,实例化后自动调用该列表

相关问题 更多 >