如何在 Python 中创建我不知道数量的对象?
How can I create objects in Python, that I don't know the quantity of?
所以,我只是在 Python 中编写一些代码,并且正在创建一个简单的贪吃蛇游戏。我想知道是否可以创建可变数量的对象。这是一个例子:
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?
将它们放入列表中:
enemies = []
while True:
enemies.append(Enemy(100))
time.sleep(60)
并通过 for 循环访问它们:
for enemy in enemies:
do_something(enemy)
所以,我只是在 Python 中编写一些代码,并且正在创建一个简单的贪吃蛇游戏。我想知道是否可以创建可变数量的对象。这是一个例子:
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?
将它们放入列表中:
enemies = []
while True:
enemies.append(Enemy(100))
time.sleep(60)
并通过 for 循环访问它们:
for enemy in enemies:
do_something(enemy)