Skip to main content
gamedev.net
🔒 Locked

Python -- creating a object dynamically from a string

Started by Tac-Tics Mar 26, 2006 at 3:43 AM 5 replies 950+ views
Original Post
Tac-Tics
Tac-Tics
Hi. I'm using python for a stratego-like game. I've run into a problem which I am sure Python can take care of very easily. I want to take a list of strings and turn them into unit objects. I have a base class called Unit. There are several subclasses such as Marshall, Bomb, Flag, Spy, General, Scout, etc. I also have a list of strings corresponding to those names. Each name appears once for every copy of that unit you start with. So, it looks like:
["General", "Major", "Major", "Major", ... ]
Since you start off with 1 general and 3 major units. What I want to do is run through this list and somehow generate the correct type of unit from a string. I would think it would follow the form:
for unit in unitNames:
   unitClass = ????(unit)
   unitList.append(apply(unitClass), ...)
Does Python have a function or way to fill in the ???? (a function to convert a string to the class/type that corresponds to that type). Thanks in advance.
Tac-Tics
Tac-Tics
Thank you all for your answers

>>Why not use a list of classes?
>>[General, Major, Major, Major, ... ]

I didn't think of that although, unlike the other ways people answered, that is the one way I *should* have known how to do it.

Still, keeping them strings making it easy if I for some reason want to write this as a *.ini file.

Thanks again all.

Topic Locked

This topic has been locked by a moderator. New replies are not allowed.

Sign in to reply to this topic.