简体   繁体   中英

How can I create objects in Python, that I don't know the quantity of?

So, I am just doing some coding in Python and I am creating a simple snake game. I was wondering if it is possible to create a variable amount of objects. This is an example:

class Enemy:
    def __init__(hp):
        self.hp = hp
        print("hp")
#So if I say, create an enemy every minute. I could use time, but then if the game lasts for 10 minutes or an hour, the number of enemies spawned will differ. How would I be able to tackle that?
#This is the only option I could think of, but this wouldn't work:
while running: #as long as the game is running
    enemy = Enemy(100) #Instantiating object
    time.sleep(60) #Sleep for 60 seconds
#This wouldn't work because the objects would need to have a different name. How can I actually do this?

Put them in a list:

enemies = []
while True:
    enemies.append(Enemy(100))
    time.sleep(60)

and access them via a for loop:

for enemy in enemies:
    do_something(enemy)

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