未定义的类实例数

2024-10-06 07:00:57 发布

您现在位置:Python中文网/ 问答频道 /正文

比方说,我有一个假设的程序或游戏与汽车类,我想创建一个新的汽车对象,任何时候的球员,如点击鼠标。在下面的示例中,我们创建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()

可能吗?怎么做


Tags: and对象nameself程序游戏ifmain
1条回答
网友
1楼 · 发布于 2024-10-06 07:00:57

您不应该在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()

但我甚至不认为每个汽车实例都需要一个唯一的密钥,而是应该创建一个list并通过索引访问所需的汽车实例

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()

相关问题 更多 >