即使他们不应该
我认为我了解指针,这是一个显示正常行为的示例:
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 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
实际上,它们具有相同的ID纯粹是偶然的,Python确定是否通过参考计数销毁对象。您不会保存每个
a(n)
的参考,这会导致它在获得其ID后立即被摧毁,因此下一个a(n)
将使用该ID与前一个相同的内存空间。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 nextA(n)
will use the same memory space as the previous one.