首页 > 解决方案 > 在函数外部引用时函数参数不变

问题描述

class ListNode:
  # initialize a node
  def __init__(self, val,next = None):
    self.val = val
    self.next = next
  
  # allows you to print the list
  def __str__(self):
    temp = self
    arr = []
    while temp!= None:
      arr.append(temp.val)
      temp = temp.next
    return "->".join([str(i) for i in arr])

def change_test(link):
    link = ListNode(5)
    print(link) # this prints 5

test = ListNode(1)
print(test) # this is expected to print 1
change_test(test)
print(test) # this is expected to print 5 but its still printing 1

我不知道为什么函数参数的状态没有保存。对于我要使用的特定用例,返回对象不是一种选择。

标签: pythonfunctionlinked-list

解决方案


那是因为您创建了一个新对象,这是您正在打印的内容,而不是ListNode您作为参数传递的对象。

我猜这就是你想要做的:

def change_test(link):
    link.val = 5
    print(link) # this prints 5

test = ListNode(1)
print(test) # this prints 1
change_test(test)
print(test) # this prints 5 as expected

推荐阅读