Xeno
Xeno

Reputation: 89

Automating creation of class instances in python for an undetermined amount of instances

I am creating a turn-based game, where the player can create units at any time during his/her turn.
A shortened version of the Unit class is:

class Unit(object):
    def __init__(self, xpos, ypos, color = 'red'):
        self.xpos = xpos
        self.ypos = ypos
        self.color = color

And I was wondering if there was a way to automate creation of instances of this class, without
hardcoding something like:

unit1 = Unit(1, 1)
unit2 = Unit(1, 2)
...
unitn = Unit(1, 2)

So that I could just make a function such as create_unit(xpos, ypos, color = 'red')
and I wouldn't have to worry about hardcoding every unit spot avaliable

Thanks in advance!

P.S. I'm using Python 2.7

Upvotes: 1

Views: 809

Answers (1)

user4266696
user4266696

Reputation:

Whenever you see the pattern: unit1, unit2, ... , unitN, you should probably be using a list to store them. If you want to create a new unit, just append a new unit to the list. Try this example:

units = []

# Your Unit constructor handles the creation of a new unit:
# No need to create a special function for that.
units.append(Unit(1,1))
units.append(Unit(1,2))

# etc...

print(units)

Upvotes: 2

Related Questions