It took me ~1 hour to find a silly bug because of the "call-by-value" thing in python:
>> a = b = {}
>> a[0] = 1
>> print a
{0:1}
>>b[0] = 9
>> print a
{0:9}
>> print id(a)
4297396640
>> print id(b)
4297396640
When you change the value of a copied variable, the formal one changes, too.
So yes, as it is confusing usually how parameters are passed in different programming languages. What happens when a variable is passed and whether its value will be changed or not.
In python, a variable actually holds a reference (pointer, address) of an object. When the variable is passed as a parameter, its value is copied into the formal parameter variable.
>>x = 1
>>print id(x)
39030144
>>def f(x):
>> print id(x)
39030144
>> x = 2
>> print id(x)
39030132
>>f(x)
>>print x
1
>> a = b = {}
>> a[0] = 1
>> print a
{0:1}
>>b[0] = 9
>> print a
{0:9}
>> print id(a)
4297396640
>> print id(b)
4297396640
When you change the value of a copied variable, the formal one changes, too.
So yes, as it is confusing usually how parameters are passed in different programming languages. What happens when a variable is passed and whether its value will be changed or not.
In python, a variable actually holds a reference (pointer, address) of an object. When the variable is passed as a parameter, its value is copied into the formal parameter variable.
>>x = 1
>>print id(x)
39030144
>>def f(x):
>> print id(x)
39030144
>> x = 2
>> print id(x)
39030132
>>f(x)
>>print x
1
Comments
Post a Comment