1

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

2
  • That create_unit function would do exactly the same thing the Unit constructor already does, so what would be the point? Commented Nov 26, 2014 at 2:20
  • 2
    Meanwhile, I'm pretty sure what you really want here is not n separate variables, but one variable with a list of n objects—e.g., units = [Unit(1, 2) for _ in range(n)]. See Keep data out of your variable names and Why you don't want to dynamically create variables. Commented Nov 26, 2014 at 2:20

1 Answer 1

2

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)
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.