Python for a PHP user, how do i...?

Magnus Lie Hetland mlh at idi.ntnu.no
Tue May 15 22:40:28 CEST 2001


"rw2" <richw at objenv.com> wrote in message
news:20010515.115853.995706887.2310 at mayne.dhcp.fnal.gov...
> In article <9dri66$202$1 at news.mty.itesm.mx>, "Eduardo Dominguez"
> <lalo_dominguez at yahoo.com> wrote:
>
> > Disclaimer: I am not trying to compare, promote or bash PHP nor Python.
> > I want to learn Python and I am curious.
> >
> > I am starting with Python, and I like it so far. But I still miss some
> > features from PHP. THis might be in python, but I havent found them yet.
> > If anyone can help me... :)
> >
> > In PHP I can call "variable" functions like:
> >   $varName = "PrintDate";
> >   $varName(); // calls function "PrintDate"

This can't be done directly in Python, but you can get pretty close.
Instead of $varName(), you use eval(varName+'()'), for instance.

> > Also, I can have variable variables, like:
> >   $tempVar = "myVar";
> >   $$tempVar = 1;
> >   echo $myVar; // echoes "1"

Hm. One version would be

  tempVar = 'myVar'
  globals()[tempVar] = 1
  print myVar

It works, but I'm not sure if it's a "good thing" :)

You could also use your own dictionary:

vars = {}
vars['tempVar'] = 'myVar'
vars[vars['tempVar']] = 1
print vars['myVar']

Even if the syntax is a bit different, the effect is quite similar to
the PHP example...

> > Can I get metadata of a class ?? for example, the name, my parents name,
> > etc ?

How about the inspect module?

> > How can I do this in Python ?
>
> You can wrap this in a function to make it a bit less clumsy, but you can
do
> something close.
>
> >>> spam="print 'eggs'"
> >>> eval(compile(spam,'<string>','exec'))
> eggs
>
> rw2

Why the compile? Why not just eval(spam)?

--

  Magnus Lie Hetland         http://www.hetland.org

 "Reality is that which, when you stop believing in
  it, doesn't go away."           -- Philip K. Dick






More information about the Python-list mailing list