assigning values in python and perl

Mel mwilson at the-wire.com
Thu Jan 17 00:54:44 EST 2008


J. Peng wrote:
> May I ask, python's pass-by-reference is passing the object's
> reference to functions, but perl, or C's pass-by-reference is passing
> the variable itself's reference to functions. So althought they're all
> called pass-by-reference,but will get different results.Is it?
> 
> On Jan 17, 2008 11:34 AM, J. Peng <peng.kyo at gmail.com> wrote:
>> I just thought python's way of assigning value to a variable is really
>> different to other language like C,perl. :)
>>
>> Below two ways (python and perl) are called "pass by reference", but
>> they get different results.
>> Yes I'm reading 'Core python programming', I know what happened, but
>> just a little confused about it.
>>
>> $ cat t1.py
>> def test(x):
>>     x = [4,5,6]
>>
>> a=[1,2,3]
>> test(a)
>> print a

As I said somewhere else, it's all about binding to names in namespaces.

a=[1,2,3]

creates a list and binds it with the name 'a' in the current namespace.

test(a) (along with def test(x)) takes the object named 'a' in the 
current namespace and binds it with the name 'x' in function test's 
local namespace.  So, inside test, the name 'x' starts by referring to 
   the list that contains [1,2,3].  But the only use test makes of the 
name 'x' is to re-bind it to a new list [4,5,6].  Exiting test, the 
local namespace is thrown away.

You could change your program a bit to clarify what's going on:

def test(x):
     print "x=", x
     x = [4,5,6]
     print "x=", x
a=[1,2,3]
test(a)
print "a=", a


	Cheers,		Mel





More information about the Python-list mailing list