Let’s say I have a class called “Map”, and Map is constructed with argument “country”. When instantiated Map should create a number of object of class “City”, based upon a list of city names for country. But how do I name the “city” objects?
pseudocode:
class Map(object):
def __init__(self, country):
for i in range(len(citynames)):
cityname_i = City(i)
In words: so let’s say I have list of citynames: [“Boston”, “Chicago”, “Denver]. When I then do something like
us_map = Map(america)
I would like Map to create three instances of class City (defined elsewhere), named “Boston”, “Chigago” and “Denver”.
I am new to this, so maybe I got my glossary OOP glossary mixed up. If so please correct me.
Edit
It seems my example created som confusion. The way I see it, my question is not about dictionaries. I just used that as an example.
I am creating a game, were people can upload any number of scenarios. I don’t know how many scenarios they are uploading. But all scenarios basically work the same way, with a number of methods. So when I create ´game = Game(folder)´ my class should create an instance of class Scenario for each uploaded scenario file. Then a third class “Engine” plays through all the scenario’s…
But how do I assign names to the instances of “Scenario” automatically?
For the moment I am using ´glob´ to find the scenario files in the relevant folder. So I have those in a list, outside the class.
UPDATE:
It seems that either I have not made my question clear (can I create instances automatically on the fly) or that good people would rather point me in the right direction, than answer my foolish question. Anyway – I think that dictionary is the way to go. So for now I am closing this question (rplnt was the first to answer) and awarding the right answer to the first poster.
Again, as in my previous answer, I would put the objects in a dictionary. Advantage over creating them in a namespace is that they will be easier to maintain. I.e. if you would create them like you said, you would still need to know about them, probably by remembering their reference stored in list (or perhaps dictionary?). If you would want to rely on the list of names, then your code would be full of
trystatements.