python - 在函数外部引用时函数参数不变
问题描述
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
我不知道为什么函数参数的状态没有保存。对于我要使用的特定用例,返回对象不是一种选择。
解决方案
那是因为您创建了一个新对象,这是您正在打印的内容,而不是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
推荐阅读
- kubernetes - 如何在 kubernetes yaml 文件中使用标签,以便系统知道推送了新图像
- c# - 如何合并文本文件并将其嵌入到 C# 代码构建中
- python - 翻转列表中的单词
- php - Laravel hasOneThrough 关系返回 null
- vba - 获取第三方 Outlook COM AddIn 的 API
- c# - ModernUi 图形未显示在应用程序中
- python - HackerRank Plus Minus ~ stdout 无响应 ~
- protocol-buffers - HTTP 请求中的 Protobuf 数据
- cmd - 如何在cmd中调用路径中的变量
- docker - java.lang.IllegalArgumentException:要求失败:sasl.mechanism.inter.broker.protocol 必须包含在 sasl.enabled.mechanisms