Matthew Cudby
Matthew Cudby

Reputation: 35

Creating class objects in a function (python)

Currently I am exploring the possibilities of Pygame and have created a simple game and am now trying to neaten it up. I am trying to define new objects by using a class I have made in a function.

This is what I tried:

def CreateEnemy():
    enemy1 = Enemies()
    enemy2 = Enemies()
    enemy3 = Enemies()
    enemy1.getInstructions()
    enemy2.getInstructions()
    enemy3.getInstructions()

However when I try to use the object enemy1 it says it is not defined. From what I know the objects may be only local in the function. Does this mean that I have to somehow use the return function?

Upvotes: 0

Views: 105

Answers (3)

Harry
Harry

Reputation: 318

please include some code so that you can get better answer but no you don't require to write return function as you can see in my example.

class Enemies:
    def getInstructions(self):
        print("Instructions")

def createEnemy():
    global allEnemy
    allEnemy.append(Enemies())

allEnemy = []
createEnemy()
createEnemy()

for enemy in allEnemy :
    enemy.getInstructions()

Upvotes: 0

Ari Gold
Ari Gold

Reputation: 1548

class Ins_Normal():
  def getInstructions(self, *args):
    return "GetInstructions_Normal"

class Ins_Agressive():
  def getInstructions(self, *args):
    return "GetInstructions_Agressive"


class Enemies(object):
  def __init__(self, behaivor = 'Ins_Normal', mode = True, *args):
    self.behaivor = behaivor
    self.mode = mode

  def getInstructions(self, *args):
    #create instance based on behaivor
    try:
        ins = globals()[self.behaivor]() # same like ins = Ins_Agressive()
    except KeyError as e:
        raise NotImplementedError(e)
    # return getInstructions() init value behaivor
    return ins.getInstructions()

  def xyz(self, *args):
    # if True return worldspace position (eg)
    if self.mode:
      return "xyz"
    return 'com_xyz'

def CreateEnemy(enemy = 0, behaivor = 'Ins_Normal', mode =True):
    # wrapper function to collect Enemies 
    # create dict, so no hardcoded variabels, scalable....
    data = dict((_id, Enemies(behaivor, mode)) for _id in range(enemy))
    return data

# create groups of enemies
enemies_com_normal = CreateEnemy(3, 'Ins_Normal') #com
enemies_user_normal = CreateEnemy(3, 'Ins_Normal', True) #interactive
enemies_com_agressive = CreateEnemy(5, 'Ins_Agressive', True) #interactive

print enemies_com_normal
# we get dict of Enemy instances with id(int) as key
#>>> {0: <Enemies object at 0x7f2d8cfe5b10>, 1: <Enemies object at 0x7f2d8cfe5b50>, 2: <Enemies object at 0x7f2d8cfe5b90>}

#lets print some infos of the agents
print enemies_com_normal[0].xyz()
#>>>xyz
print enemies_com_normal[0].getInstructions()
#>>>GetInstructions_Normal
print enemies_com_agressive[2].getInstructions()
#>>>GetInstructions_Agressive

enemies_com_hgd = CreateEnemy(5, 'Ins_HGD', True) #interactive
print enemies_com_hgd[0].getInstructions()

#Traceback (most recent call last):
#  File "python", line 56, in <module>
#  File "python", line 21, in getInstructions
#NotImplementedError: 'Ins_HGD' <<<<< no Instruction Implemented for  Ins_HGD

Upvotes: 0

gipsy
gipsy

Reputation: 3859

I am assuming you have a class called Enemies something like below

class Enemies:
  def getInstructions():
    return "instructions"

now want a method to create a bunch of enemies instances

def create_enemies(num_of_enemies):
  enemies = []
  for i in range(num_of_enemies):
    enemies.append(enemy)
  return enemies

and then use the above method to create enemies like this:

enemy1, enemy2 , enemy3 = create_enemies(3)

Upvotes: 1

Related Questions