简体   繁体   中英

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. 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.

This is the class I defined:

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 . I have two ways to do so:

(1)

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

or (2)

objects = [Objects()] * k

(1) gives me the result I want, ie each instance has an incremental 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?

In addition, I mostly do OOP in Java, and this is how I implement incremental ID. I don't know if this applies to Python as well.

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. It creates k objects.

2 is probably not what you want. It creates only one object and then a list 'pointing' k times to the same object.

Use following command to visualize the result of 1 and of 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.

board = [[0] * 8] * 8  

which creates one row of zeroes, which is referenced 8 times.

to have 8 different rows you had to type

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

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

will show the difference

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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