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

Alex Martelli aleaxit at yahoo.com
Tue May 15 15:50:07 EDT 2001


"Eduardo Dominguez" <lalo_dominguez at yahoo.com> wrote in message
news:9dri66$202$1 at news.mty.itesm.mx...
    [snip]
> In PHP I can call "variable" functions like:
>   $varName = "PrintDate";
>   $varName(); // calls function "PrintDate"

In Python, you do *nothing BUT* "calling variable
functions".
    varName = PrintDate
    varName()    # calls function PrintDate

Functions are first-class objects and can be handled
in all ways other objects can be handled.  Any
identifier you may use to refer to a function object
IS always a variable, whether it's been bound to
the function object by 'from', 'def', or assignment.


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

The simplest way to achieve this kind of effect is
by using a dictionary:
    x = {}
    tempVar = 'myVar'
    x[tempVar] = 1
    print x['myVar']

There are several ways to 'dress up' this dictionary
in arguably-prettier syntax sugar.  For example, if
you start with
    x = globals()
(although this is NOT recommended...), you can
later use a statement such as:
    print myVar
as equivalent to:
    print x['myVar']

Dressing it up in an object is probably best:
    class X: pass
    x = X()
    tempVar = 'myVar'
    setattr(x, tempVar, 1)
    print x.myVar


Worst-case, you CAN use exec and eval() to achieve
such effects.  But, it *IS* the worst-case: it's a choice
to compromise program solidity and clarity in the quest
for very debatable syntax-sugar "advantages".


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

You can get metadata for any object, including both a
class and an instance.  For example, after executing the
latest snippet above, X.__name__ is 'X', X.__bases__
is the empty tuple, x.__class__ is X, etc.  Most objects
don't "know their name" because there IS no privileged
name (out of the many that might be used to refer to
them), but classes, functions, and modules do.


> One thing I _really_ miss is an anotated manual. PHP
> has a great one and that really helps people start with PHP.

Python's tutorial is pretty good (for people already
experienced in other languages) and so is the library
manual.  The language reference IS written, as it
says, 'for language lawyers', admittedly -- something
between the tutorial and the language reference might
perhaps help, but the free documentation situation for
Python IS pretty good, and there are many good books
available too.


Alex






More information about the Python-list mailing list