简体   繁体   English

列表理解中的指针都相同,即使它们不应该

[英]pointers all the same in list comprehension even though they shouldn't

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.指针和属性之间的区别可以用两个完全相同的对象来举例说明,这些对象具有相同的属性但是是不同的对象,因此具有不同的指针。

In fact, it is purely coincidental that they have the same id, Python determines whether to destroy an object by reference counting.其实它们的id相同纯属巧合,Python通过引用计数来判断是否销毁一个对象。 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.您不保存每个A(n)的引用,这会导致它在您获得其 id 后立即被销毁,因此下一个A(n)将使用与前一个相同的内存空间。

>>> [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]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 具有自定义元类的类的所有子类共享相同的属性,即使它们不应该共享 - All subclasses of a class with a custom metaclass share the same attributes even though they shouldn't pyqt4中的按钮最终具有相同的事件处理程序,即使它们不应该 - Buttons in pyqt4 end up having the same event handler even though they shouldn't Python的subprocess.Popen即使不应该返回相同的stdout - Python's subprocess.Popen returns the same stdout even though it shouldn't 嵌套理解列表:即使在循环内,变量也不存在 - nested comprehension list: variable doesn't exist even though inside loop 语法错误,即使不应该出现语法错误(.configure()) - Syntax Error even though there shouldn't be a Syntax Error (.configure()) 有一个while循环的问题,它会中断,即使它不应该 - Having trouble with a while loop, it breaks, even though it shouldn't 设置大小正在变化,即使它不应该是python - set size is changing even though it shouldn't python AI问题(即使它不应该碰撞自己) - AI problem (Colliding on itself even though it shouldn't) findContours 是否有原因给我一个错误,即使它不应该? - Is there a reason findContours is giving me an error even though it shouldn't? 为什么列表理解与没有理解的代码的工作方式不同? - Why list comprehension doesn't work the same as code without comprehension?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM