如果我们在Python中更改对象的引用,为什么它有时会更改对象的id(内存位置)?
我试图实现链表的节点并遇到以下问题:当我将新对象分配给 m2,然后将新变量 c 分配给关联的旧对象时使用 m2
它会返回相同的 id。
class Node:
def __init__(self,dataval=None):
self.val = dataval ##Int
self.nextval = None ##Node
class SLinkedList:
def __init__(self,headval=None):
self.headval = headval ##Node
m2 = Node(4)
print(id(m2)) # Returns 2309784010704
m2 = Node(5)
c = Node(4) # Assigning same object as previously with m2
print(id(c)) # Returns 2309784010704 which is same as id of m2
但是,如果我不更改 m2
的值,如下所示,那么它会显示 m2
和 c
的不同 id 位置。
class Node:
def __init__(self,dataval=None):
self.val = dataval ##Int
self.nextval = None ##Node
class SLinkedList:
def __init__(self,headval=None):
self.headval = headval ##Node
m2 = Node(4)
print(id(m2)) # Returns 2582642884560
c = Node(4)
print(id(c)) # Returns 2582642884320 which is not same as id of m2
我无法知道为什么在第一个代码中,c
的 id 与 m2
的先前 id 相同,而不是不为其分配新的内存位置。
I was trying to implement a node for linked list and faced the following issue: When I assign a new object to m2
and then assign the new variable c
to the old object associated with m2
it gives back the same id.
class Node:
def __init__(self,dataval=None):
self.val = dataval ##Int
self.nextval = None ##Node
class SLinkedList:
def __init__(self,headval=None):
self.headval = headval ##Node
m2 = Node(4)
print(id(m2)) # Returns 2309784010704
m2 = Node(5)
c = Node(4) # Assigning same object as previously with m2
print(id(c)) # Returns 2309784010704 which is same as id of m2
But if I don't change value of m2
as shown below then it shows different id locations of m2
and c
.
class Node:
def __init__(self,dataval=None):
self.val = dataval ##Int
self.nextval = None ##Node
class SLinkedList:
def __init__(self,headval=None):
self.headval = headval ##Node
m2 = Node(4)
print(id(m2)) # Returns 2582642884560
c = Node(4)
print(id(c)) # Returns 2582642884320 which is not same as id of m2
I was not able to know the reason why in first code, id of c
is same as previous id of m2
rather than not assigning it a new memory location.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论