Onebus
Onebus

Reputation: 1

Undefined number of class instances

Let's say I have a hypothetical program or game with class Car and I want to create a new car object any time players e.g click mouse. In folowing example we create newCarNrI; I want be able to create : newCarNr1, newCarNr2, newCarNr3, newCarNr4, newCarNr5 on every click.

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

Is it possible? How to do it?

Upvotes: 0

Views: 38

Answers (1)

Taku
Taku

Reputation: 33724

You should not create that many names in the locals() scope, try using a dict and save it as key and values.

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

But I don't even believe you need to have an unique key for every Car instance, you should instead make a list and access the Car instance you wanted by indexing.

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

Upvotes: 2

Related Questions