Skip to main content
 首页 » 编程设计

Python : why doesn't a. pop() 修改链表(自定义链表类)

2025年04月02日8leader

我正在尝试定义一个链表类 Hlist,如下所示:

class Hlist: 
 
def __init__(self, value, hlnext): 
    self.value = value 
    self.hlnext = hlnext 
 
def pop(self): 
    res = self.value 
    if not(self.hlnext == None): 
        self = self.hlnext 
    return res 
 
def __repr__(self): 
    return (str(self.value) + ' - ' +  str(self.hlnext)) 

当我在

上测试 pop() 方法时
a = Hlist(1, Hlist(2, None)) 

Python 返回 1 - 2 - 无,好的。然后

a.pop() 

返回 1,很好。然而:

print(a) 

返回 1 - 2 - 无。列表没有被修改,尽管

self = self.hlnext 

self 是指针 a 还是指向与 a 相同地址的另一个指针? 为什么以下代码会返回 pop() 的预期答案:

class Hlist: 
 
def __init__(self, value, hlnext): 
    self.value = value 
    self.hlnext = hlnext 
 
def pop(self): 
    res = self.value 
    if not(self.hlnext == None): 
        self.value = self.hlnext.value 
        self.next = self.hlnext.hlnext 
    return res 
 
def __repr__(self): 
    return (str(self.value) + ' - ' +  str(self.hlnext)) 

是不是因为python使用了setattr函数?

实际上,我试图在 Python 中获得与 Java 中以下类的等效项:

class Hlist{ 
    int value; 
    Hlist hlnext; 
 
    Hlist(int value,Hlist hlnext){ 
        value = value; 
        hlnext = hlnext; 
    } 
} 

并为其添加一个 pop() 方法。在 pop() 方法中,Java 的 this 会像 Python 的 self 一样工作(局部变量)还是会绑定(bind)到我称为 pop() 的指针?在这种情况下,this = this.hlnext 是否会更改 a 指针?

请您参考如下方法:

因为 self 并没有按照您认为的方式工作。 self 只是另一个局部变量:在 pop() 中分配给它不会将对象变成另一个东西。参见 this question了解更多详情。