【问题标题】:Same list address in memory for two different instantiations of the class对于类的两个不同实例,内存中的相同列表地址
【发布时间】:2018-08-01 05:18:05
【问题描述】:

我有以下代码:

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

【问题讨论】:

    标签: python list class memory


    【解决方案1】:

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

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

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

    【讨论】:

    • 感谢您的快速响应,它完美无缺。
    【解决方案2】:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-04-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-09-24
      相关资源
      最近更新 更多