即使他们不应该

发布于 2025-01-30 06:07:04 字数 741 浏览 1 评论 0原文

我认为我了解指针,这是一个显示正常行为的示例:

class A:
  def __init__(self, n):
      self.n = n
a = A(1)
b = A(1)
print(id(a))
print(id(b))

输出是:

001 | 140441581640704
002 | 140441581640608

但是,当我执行此代码(在列表中创建对象)时,

class A:
  def __init__(self, n):
      self.n = n

a = [id(A(n)) for n in range(5)]

print(a)

我会得到此输出:

[140270531148816, 140270531148816, 140270531148816, 140270531148816, 140270531148816]

哪个更糟(我猜?),因为它不是甚至具有相同属性的对象。指针和属性之间的差异被用两个具有相同属性但具有不同对象的对象的相同对象举例说明,因此具有不同的指针。

I think I understand pointers, here is an example showing a normal behaviour:

class A:
  def __init__(self, n):
      self.n = n
a = A(1)
b = A(1)
print(id(a))
print(id(b))

Output is:

001 | 140441581640704
002 | 140441581640608

However, when I execute this code (creating objects in a list comprehension)

class A:
  def __init__(self, n):
      self.n = n

a = [id(A(n)) for n in range(5)]

print(a)

I get this output:

[140270531148816, 140270531148816, 140270531148816, 140270531148816, 140270531148816]

Which is even worse (I guess?) because it's not even objects with the same attributes. The difference between pointers and attributes being exemplified with two exact same objects that have same attributes but are different objects so have different pointers.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

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

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

万劫不复 2025-02-06 06:07:04

实际上,它们具有相同的ID纯粹是偶然的,Python确定是否通过参考计数销毁对象。您不会保存每个a(n)的参考,这会导致它在获得其ID后立即被摧毁,因此下一个a(n)将使用该ID与前一个相同的内存空间。

>>> [id(A(n)) for n in range(5)]
[2014694650160, 2014694650160, 2014694650160, 2014694650160, 2014694650160]
>>> [id(a) for a in [A(n) for n in range(5)]]
[2014694650208, 2014694637632, 2014694649440, 2014694653808, 2014694649536]

In fact, it is purely coincidental that they have the same id, Python determines whether to destroy an object by reference counting. You don't save the reference of each A(n), which causes it be destroied immediately after you get its id, so the next A(n) will use the same memory space as the previous one.

>>> [id(A(n)) for n in range(5)]
[2014694650160, 2014694650160, 2014694650160, 2014694650160, 2014694650160]
>>> [id(a) for a in [A(n) for n in range(5)]]
[2014694650208, 2014694637632, 2014694649440, 2014694653808, 2014694649536]
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文