[Tutor] user-given variable names for objects

Alan Gauld alan.gauld at btinternet.com
Thu Dec 13 08:53:36 CET 2007

"Che M" <pine508 at hotmail.com> wrote 

> I'm sure this is a classic beginner's topic, 

Indeed it is, it comes up about once a month or more!

> I want to assign names to objects based on what a 
> user inputs so that I can later keep track of them. 

This is almost never what you want to do, for precisely 
the reason that you can't keep trackl of them when you 
stop using the >>> prompt. Insteaed you should probably 
use a dictionary to collect these user based objects 
based on their names.

There is a section  on this in the OOP topic in my tutorial

> ...In order to do this, I need to give each start time 
> a name associated with the name of the event.  
> If there is an "event A" it's start time could be 
> eventA_start, whereas event B could be called eventB_start

So create a dictionary called events and access them using



> The problem is, I don't know the "A" part... the user could 
> choose eventPotato or eventDinosaur.  I won't know in advance.  

Which is why you can't write code to use variables whose 
names you don't know when writing the code. That's why putting 
them in a dictionary is a better solution. You just get the name 
as a string and use it as a key in the dictionary. Just watch out 
for duplicate names.

> I have read that the way to do this properly in Python is with 
> use of dictionaries, but I haven't found a reference online that 
> shows how to do it is in a complete way.  Any help is appreciated.

Check the bank account example in my tutorial, under the 
section heading "collections of objects".


Alan Gauld
Author of the Learn to Program web site

More information about the Tutor mailing list