newbie question

Martijn Faassen m.faassen at vet.uu.nl
Sat May 26 21:04:52 EDT 2001


Jasonbail <jasonbail at aol.com> wrote:
> I'm fairly new to programming,

> My questions is, is there anyway to create a reference to a pre-existing
> variable by using variables?

> for example if I have a variable daily_count

> can I access that variable by using "daily_" and "count" thats stored in other
> variables?

Since you are new to programming, I think the best answer here would
be to ask you some more questions. The most important one in these cases
is always: 

  Why would you want to do that?

Presumably you have a problem you're trying to solve, and you are looking
along these lines for a solution. My question already implies that perhaps
there are other avenues to take that avoid this problem completely, and
that would be much easier to implement. So tell us why you'd like to do 
this.

I'll now add some more questions to make clear why your approach may
not be the best one:

  Where is your variable 'daily_count' defined? As a local variable
  in a function or a method? As a global variable in a module? (are
  you using interactive mode?) As the attribute of an object?

Another important question:

  Are you interested in the name of the variable, or what the variable
  actually refers to? 

In Python, variables (attributes, etc, in python terminology, names) are
always references to *objects*. The only way you can approach objects is
to go through these names in some fashion. The objects contain the data
and define the behavior, however. The names may refer to one object now,
and another in the future. Multiple names can refer to the same object.
This distinction between names and the objects they refer to is very
important in Python, so you make sure you clearly understand this. It
is not extremely difficult to understand and to deal with once you
understand, but it is a common problem for many that are new to Python.

Names cannot refer to other names, only to objects.

There is trickery to make names refer to other names indirectly, and
some of the other posters may describe how to do this. I'll name the built-in
getattr() function, which allows you to get the named attribute of any
object in Python, for instance. This is frequently useful. Accessing local 
or global variables is more difficult, and generally is not done except in
very special programs.

I cannot tell you much more that seems useful to you, however. So,
again, please tell us what you're trying to accomplish. Also, if you have
any question about what I just told you, be sure to ask those as well.

Regards and good luck,

Martijn
-- 
History of the 20th Century: WW1, WW2, WW3?
No, WWW -- Could we be going in the right direction?



More information about the Python-list mailing list