Passing parameters to functions and methods. Pass-by-value? Pass-by-reference? Which does your language use?
You probably learned this in your first CS class... so did I.
Then why did it take me a frakin' month to understand what Python does? :)
Well... if you look online, you will find some very ambiguous answers about Python being pass-by-reference or pass-by-value. (which ends up boiling down to semantics and how you use certain terminology, but forget that for now)
To review, how do other languages handle this concept?
C is pass-by-value
Straightforward. You can simulate pass-by-reference with pointers. Not much else to say here.
Java is pass-by-value
Primitive Types (non-object built-in types) are simply passed by value. Passing Object References feels like pass-by-reference, but it isn't. What you are really doing is passing references-to-objects by value.
OK, so what about Python?
Python passes references to objects by value (like Java), and everything in Python is an object. This sounds simple, but then you will notice that some data types seem to exhibit pass-by-value characteristics, while others seem to act like pass-by-reference... what's the deal?
It is important to understand mutable and immutable objects. Some objects, like strings, tuples, and numbers, are immutable. Altering them inside a function/method will create a new instance and the original instance outside the function/method is not changed. Other objects, like lists and dictionaries are mutable, which means you can change the object in-place. Therefore, altering an object inside a function/method will also change the original object outside.
For entirely too much information about this topic in Python and across many other languages (Java, Scheme, C#, C, C++, Python), read the thread where these quotes come from:
Is Python By Value Or By Reference?
Alex Martelli:
The terminology problem may be due to the fact that, in python, the value of a name is a reference to an object. So, you always pass the value (no implicit copying), and that value is always a reference. [...] Now if you want to coin a name for that, such as "by object reference", "by uncopied value", or whatever, be my guest. Trying to reuse terminology that is more generally applied to languages where "variables are boxes" to a language where "variables are post-it tags" is, IMHO, more likely to confuse than to help.
Michael Hoffman:
Alex is right that trying to shoehorn Python into a "pass-by-reference" or "pass-by-value" paradigm is misleading and probably not very helpful. In Python every variable assignment (even an assignment of a small integer) is an assignment of a reference. Every function call involves passing the values of those references.
word.
Copyright © 2006-2008 Corey Goldberg
Disclaimer The opinions expressed herein are my own personal opinions and do not represent my employer's view in any way.