修改函数中的类以反映呼叫功能的变化(Python)
我的类如下:
class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
我创建一个链接列表为:
ll = ListNode(1)
ll.next = ListNode(2)
我想通过函数中的创建新节点将列表复制到新列表:
def create_new_node(res, l):
print(l.val)
res.next = ListNode(l.val)
l=l.next
print("Next", l.val)
res=res.next
res = ListNode()
while ll:
# Based on some condition
create_new_node(res, ll)
>>> 1
Next 2
1
Next 2
....
但是,由于ll
,这将变成无限循环。在create_node_function
之外,切勿在while循环中进行下一个节点,即使l
(这是ll
)的引用)要指向next
节点为l = l.next
。
是否不在Python中的参考中通过类,并且不能在另一个函数中修改它们以反映调用函数的更改吗?
I have a class as follows:
class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
I create a linked list as:
ll = ListNode(1)
ll.next = ListNode(2)
I want to copy the list to a new list by create new nodes in a function:
def create_new_node(res, l):
print(l.val)
res.next = ListNode(l.val)
l=l.next
print("Next", l.val)
res=res.next
res = ListNode()
while ll:
# Based on some condition
create_new_node(res, ll)
>>> 1
Next 2
1
Next 2
....
However, this goes into a infinite loop since the ll
never progresses to the next node in the while loop outside of the create_node_function
even though l
(which is a reference of ll
) is being made to point to the next
node as l=l.next
.
Are classes not passed by reference in Python, and can they not be modified in another function to reflect the changes in the calling function?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
在Python中,对象通过分配传递。您可以使用以下代码看到此信息。
输出是:
您会看到函数内部和外部ID相同,因此它们的值相同。但是,当您更改可变对象时,ID的保持不变,并且使用不变的对象ID会更改。
课堂实例是可变的,因此它们的作用与参考的通过相似。我们可以通过在以下代码中检查每个对象上的ID,可以看到这一点。
输出是
您的代码的问题是
当我们将ll传递到create_new_node l是ll时,但是当我们将l设置为l.next时,l现在是l.next而不是ll,l.next在内存中具有不同的地址。为了使您的代码工作并复制列表返回l。
In python objects are passed by assignment. You can see this with the following code.
the output is:
You see the id's inside and outside the function are the same, so they are the same value. However, when you change a mutable object the id's stays the same and with immutable objects the id changes.
Class instances are mutable so they will act similar to pass by reference. We can see this by checking the id's on each object in the following code.
the output is
The problem with your code is the line
when we pass ll into create_new_node l is ll but when we set l to l.next, l is now l.next and not ll, l.next has a different address in memory. To make your code work and copy the list return l like so.