function/method assigment

Bruno Desthuilliers bruno.42.desthuilliers at wtf.websiteburo.oops.com
Fri Apr 13 12:43:56 EDT 2007


viscroad at gmail.com a écrit :
> I have a confusion when I do some practice, the code and output are as
> following,
> 
>>>> def fun():
> 	print 'In fun()....'

Function fun doesn't explicitelly return something, so it's return value
defaults to None (nb: None is a builtin object representing 'nothing').

> 
>>>> testfun = fun()

This calls fun, and binds the returned value (in this case, None) to
name testfun

> In fun()....

and this is a side-effect of the execution of function fun.

>>>> print testfun
> None

Which is the expected result

>>>> testfun2 = fun

This binds the function object fun to the name testfun2 (IOW, testfun2
is now an alias for fun). Remember that in Python, the parens are not
optional if you want to call a function - they are in fact the 'call
operator'. If you forget them, you get a reference to the function
object, not the result of calling the function.

>>>> print testfun2
This prints the representation of the object bound to name testfun2 -
here, function fun.

> <function fun at 0x00CC1270>
>>>> print testfun2()
> In fun()....
> None

This first calls testfun2 (which is now another name for function fun),
triggering the printing of the string "in fun()..." as a side effects,
then print the return value of testfun2 (aka fun), which is still None.

HTH



More information about the Python-list mailing list