dsh8290 at rit.edu
Fri May 25 18:10:03 CEST 2001
On Fri, May 25, 2001 at 10:12:24AM -0500, Enrico Ng wrote:
| I want to pass by reference a variable to a function.
| how to I pass the address of a variable.
| & doesnt work.
& works just fine -- except it doesn't mean "address of" as in C. ;-)
In Python functions, classes and modules are all first-class objects.
What this means is that a function is an object just like the string
"Hello World". Passing a reference to the function is exactly like
passing a reference to a string. Here is an example:
def func( arg1 , arg2 ) :
print "func was called with arguments '%s' and '%s'" % ( arg1 , arg2 )
def call_a_function( function ) :
# the argument 'function' should be a reference to a function
# (or any other callable) object. It will be called with 2
function( "Hello World" , "In Python simple things are still simple!" )
# here is the "main", where we pass a reference to a function to
# another function
call_a_function( func )
In Python _all_ lines are executable statements. Even "def" and
"class". The "def" statement creates a new name in the current scope
and binds it to the function object that is defined by the body of the
function. Thus functions are quite orthogonal because they behave as
all other objects. This is in contrast to C, C++, and Java where
function/method definitions are special -- the compiler creates a
space in memory for the resulting code to lie, but the function
"object" exists only during the compilation phase. A tag is put in
the "object file" (.o or .class) to the function so the linker knows
where to jump to when the function is called, but at runtime the
functions (and classes) aren't actual objects. In Java you can do
introspection on classes, etc, but it isn't pretty -- nowhere near as
simple and concise and understandable as Python's introspection.
More information about the Python-list