未定义的类实例数

时间:2017-05-21 16:16:21

标签: python class oop pygame

假设我有一个假设的程序或带有Car类的游戏,我想在任何时候玩家点击鼠标时创建一个新的汽车对象。在下面的示例中,我们创建了newCarNrI;我希望能够在每次点击时创建:newCarNr1, newCarNr2, newCarNr3, newCarNr4, newCarNr5

import pygame

class Car:
   def __init__(self,name):
      self.name = name

def main():

   #pygame initialisation and logic and stuff ...

   #game Loop
   while True:
      click = pygame.mouse.get_pressed()
      if click[0] == 1:
         # Create new Car object when click
          newCarNrI = Car(aCarName)

if __name__ = '__mian__':
   main()

有可能吗?怎么做?

1 个答案:

答案 0 :(得分:2)

您不应在locals()范围内创建那么多名称,请尝试使用dict并将其另存为键和值。

import pygame

class Car:
   def __init__(self,name):
      self.name = name

def main():

   #pygame initialisation and logic and stuff ...

   #game Loop
   counter = 0
   cardict = {}
   while True:
      click = pygame.mouse.get_pressed()
      if click[0] == 1:
         counter += 1
         # Create new Car object when click
         cardict['newCarNr%i' % counter] = Car("aCarName")
    # access cardict["newCarNr7"] Car instance later

if __name__ = '__main__':
   main()

但我甚至不相信你需要为每个Car实例都有一个唯一的密钥,你应该创建一个list并通过索引访问你想要的Car实例。

import pygame

class Car:
   def __init__(self,name):
      self.name = name

def main():

   #pygame initialisation and logic and stuff ...

   #game Loop

   carlist = []
   while True:
      click = pygame.mouse.get_pressed()
      if click[0] == 1:
         # Create new Car object when click
         carlist.append(Car("aCarName"))
    # access carlist[7] Car instance later

if __name__ = '__main__':
   main()