Pass by Assignment
00:12 Python doesn’t use either pass by value or pass by reference. It uses something called pass by assignment. Other names for this include pass by object, pass by object reference, and pass by sharing.
But I’ll be using the phrase “pass by assignment.” It’s based on the following: First, everything in Python is an object. When you assign a variable to the value
5, an object representing the value
5 is created and then associated with that variable name.
01:22 So, reassigning a parameter value has no effect on the argument variable. As I said, I’ll go into more detail on assignments and bindings in an upcoming lesson, but for now, let’s take a look at the effects of reassigning a parameter variable in a Python function.
Here’s a Python version of the same program from the last lesson that you saw on C++. Because Python’s assignment statements are much more closely tied to objects, in addition to the variable’s value, you’ll see the result of calling the
id() function on each variable’s name.
Recall that every distinct object in Python has a unique ID number, which is returned by this function. But otherwise, it’s the same program. It defines a function
f() that takes a single parameter
reassigns the parameter variable, then displays this new value. In the main script, it creates a variable
x and assigns it a value, displays the value, uses the variable as the argument to the function
f(), and then prints the value of that object once again.
03:50 Each time a Python program is run, it’ll generate new ID numbers for all of its objects. See, even if I run this a second time, I get a different set of numbers, but we still see the same effect.
The first, second, and last lines are all showing references to the same object. It’s only the third line where the new object was created and bound to the parameter variable
fx is the ID number different than in the other lines.
04:28 I’ll have in a future lesson more to say about Python’s object binding, but first you should look at how Python’s mechanism does—or at least can be made to—provide some of the benefits pass by reference has.
Become a Member to join the conversation.