Skip to main content
 首页 » 编程设计

Python 引用资料

2025年05月04日1152php

我遇到过一种情况,我认为这表明我对引用在 Python 中的工作方式的理解存在差距。

假设我们有两个类:

class A: 
    def __init__(self): 
        self.x = [1,2,3] 
 
    def modify(self): 
        self.x.append(4) 
 
    def reset(self): 
        self.x = [] 
 
class B: 
    def __init__(self, x): 
        self._x = x 
 
    def say(self): 
        print self._x 
 
 
 
 
a = A() 
b = B(a.x) 
 
b.say() 
a.modify() 
b.say() 
a.reset() 
b.say() 

我期望的输出是:

[1, 2, 3] 
[1, 2, 3, 4] 
[] 

我得到的输出是:

[1, 2, 3] 
[1, 2, 3, 4] 
[1, 2, 3, 4] 

似乎当我调用reset() 并将self.x 设置为新列表时,B 持有的引用变得独立并继续存在,从而成为副本而不是引用。这是正确的理解吗?

请您参考如下方法:

reset() 方法

def reset(self): 
    self.x = [] 

不会修改存储在 self.x 中的对象——它会创建一个新的空列表,然后将其存储在 self.x 中。旧列表没有改变(因为它仍然被 b._x 引用,所以它也没有被垃圾收集)。要获得您想要的行为,请使用

def reset(self): 
    del self.x[:] 

清空现有列表而不是创建新列表。