如果我们在Python中更改对象的引用,为什么它有时会更改对象的id(内存位置)?

发布于 2025-01-10 11:30:44 字数 1057 浏览 0 评论 0原文

我试图实现链表的节点并遇到以下问题:当我将新对象分配给 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 的值,如下所示,那么它会显示 m2c 的不同 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 m2and 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文