Migrating from PHP to Python...

Joal Heagney s713221 at student.gu.edu.au
Mon Sep 3 23:55:44 EDT 2001


Joal Heagney wrote:
> 
> Rick Shin wrote:
> >
> > >
> > > All variables in python are dynamic type. Is that what you were asking?
> > >
> > > >>> a=1
> > > >>> a
> > > 1
> > > >>> a = 'hello'
> > > >>> a
> > > 'hello'
> >
> > Actually, I was referring to PHP's ability to assign names dynamically to
> > variables. For example:
> >
> > $var = 'hello';
> > $$var = 'world!';
> > echo $var . ' ' . $$var;    // prints 'hello world!'
> > echo $var . ' ' . $hello;    // prints 'hello world!' too
> 
> You mean like this?

Okay, not what you're asking for. So if I see it correctly, you've put
text into the variable $var. Then you've defined another variable that
can be called as $$var or as $hello, the string value in $var? *suddenly
locked into problem-solving mode* Sorry if I don't get an answer to you
soon enough before you reply to the prior post, but I think I can see a
way to get that behaviour.

Basically, as I see it, you've got two names for the one variable, and
one of the variable names is based on the value in another variable, and
this doesn't occur automatically. (I spent 1/2 hour trying to make a
datatype that would behave like that.)

Try this:
>>> var = 'hello' 
>>> var2 = 'world' 
>>> exec("%s = '%s'" % (var, var2)) 
>>> hello 
'world'

Of course this only works for strings, as variable names are stored as
strings inside a dictionary datatype which can be accessed by the
function dir.
>>> dir()
['__builtins__', '__doc__', '__name__', 'hello', 'var', 'var2']

It's-actually-a-little-bit-more-complex-'ly yours,
-- 
      Joal Heagney is: _____           _____
   /\ _     __   __ _    |     | _  ___  |
  /__\|\  ||   ||__ |\  || |___|/_\|___] |
 /    \ \_||__ ||___| \_|! |   |   \   \ !



More information about the Python-list mailing list