【问题标题】:Function paramater not changing when referenced outside of function在函数外部引用时函数参数不变
【发布时间】:2021-02-25 02:32:22
【问题描述】:
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

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

【问题讨论】:

    标签: python function linked-list


    【解决方案1】:

    这是因为您创建了一个新对象,这是您要打印的内容,而不是您作为参数传递的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
    

    【讨论】:

      猜你喜欢
      • 2013-06-23
      • 2019-12-10
      • 2019-03-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多