简体   繁体   English

Python 在我们使用列表推导时并行创建对象

[英]Python creates objects in parallel when we use list comprehension

I happened to bump into this problem when coding some simple object-oriented stuff in Python.在 Python 中编写一些简单的面向对象的东西时,我碰巧遇到了这个问题。 Let's say I created a class with an incremental ID (using static variable), and initialized new objects of that class, expecting the ID of each new instance to be automatically increased by 1.假设我创建了一个带有增量 ID 的 class(使用 static 变量),并初始化了该 class 的新对象,期望每个新实例的 ID 自动增加 1。

This is the class I defined:这是我定义的 class :

class Object:
   counter = 0

   def __init__(self):
      self.id = Object.counter
      Object.counter += 1

Then, I created a fixed-length array containing k instances of type Object .然后,我创建了一个固定长度的数组,其中包含 k 个类型为Object的实例。 I have two ways to do so:我有两种方法可以做到这一点:

(1) (1)

objects = [Object() for i in range(k)]

or (2)或 (2)

objects = [Objects()] * k

(1) gives me the result I want, ie each instance has an incremental ID. (1) 给了我想要的结果,即每个实例都有一个增量ID。 Interestingly, (2) produces instances that all have the same ID = 0. So I guess (2) does the same thing as (1) but in parallel?有趣的是,(2)产生的实例都具有相同的 ID = 0。所以我猜(2)与(1)做同样的事情,但并行?

In addition, I mostly do OOP in Java, and this is how I implement incremental ID.另外,我在Java中主要是做OOP,这就是我实现增量ID的方式。 I don't know if this applies to Python as well.我不知道这是否也适用于 Python。

I'm sorry if my question is redundant.如果我的问题是多余的,我很抱歉。 I don't really know how to call this kind of thing I'm doing (list comprehension, I guess).我真的不知道如何称呼我正在做的这种事情(我猜是列表理解)。

Many thanks in advance for your reply!非常感谢您的回复!

1 is the correct way of doing. 1是正确的做法。 It creates k objects.它创建 k 个对象。

2 is probably not what you want. 2 可能不是你想要的。 It creates only one object and then a list 'pointing' k times to the same object.它只创建一个 object,然后创建一个列表“指向”k 次指向同一个 object。

Use following command to visualize the result of 1 and of 2使用以下命令可视化 1 和 2 的结果

print(list(id(obj) for obj in objects))

Such error (as in 2) can be encountered quite often by many people trying to implement the first time in their life a 2 dimensional array eg for a chess board.这种错误(如在 2 中)可能会经常遇到许多人试图在他们的生命中第一次实现二维数组,例如棋盘。

board = [[0] * 8] * 8  

which creates one row of zeroes, which is referenced 8 times.它创建一行零,被引用 8 次。

to have 8 different rows you had to type有 8 个不同的行,你必须输入

board = [([0] * 8) for row in range(8)]

print([id(row) for row in board])

will show the difference将显示差异

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM