[Tutor] user-given variable names for objects
Che M
pine508 at hotmail.com
Thu Dec 13 09:57:57 CET 2007
> To: tutor at python.org
> From: alan.gauld at btinternet.com
> Date: Thu, 13 Dec 2007 07:53:36 +0000
> Subject: Re: [Tutor] user-given variable names for objects
>
>
> "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
>
> events['A']
> events['B']
>
> etc.
>
> > 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".
>
> HTH,
>
> --
> Alan Gauld
> Author of the Learn to Program web site
> http://www.freenetpages.co.uk/hp/alan.gauld
>
Thank you, indeed it did help. For some reason when I was reading
about dictionaries online I got the unfortunate thought that the value
couldn't be a function--glad I was highly incorrect on that one. I had
also been shy of understanding how to use dictionaries for some reason (fear of hyphens and curly braces?),
but your section and a little trying it out in IDLE makes it seem
do-able. I'll give it more of a go later and see if I can get things
moving ahead.
_________________________________________________________________
The best games are on Xbox 360. Click here for a special offer on an Xbox 360 Console.
http://www.xbox.com/en-US/hardware/wheretobuy/
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20071213/20460237/attachment-0001.htm
More information about the Tutor
mailing list