Assignment in Python
00:12 Recall some things I’ve already mentioned: Assignment is the process of binding a name to an object. Parameter names are also bound to objects on function entry in Python. And again, this is how Python’s argument passing mechanism gets its name.
In other languages like C++, assignment is quite simple, especially for basic types. In the first statement, a space of memory which has been designated for the variable
x has the value
5 stored in it.
Python works much differently. In the first statement, an object representing the number
5 is created, if one doesn’t already exist, and then
x is made to refer—or we sometimes say “point”—to that object, basically by storing the memory address to where the object
5 is stored.
Let’s look at this process in more detail. There’s a particular structure used to implement objects in Python. A reference counter keeps track of how many references a specific object has. So again, in the statement
x = 5, an object representing the value
5 is found or created, the reference counter for that object is incremented, and an entry is made binding that variable name to the object.
x is reassigned to the value
10, the reference count for the object representing
5 is reduced by one, the reference counter for the object representing
10 is increased by one, and finally, the appropriate dictionary is updated to indicate that
x is now bound to that new object
10. To see this happen, you can write a small program which uses the
This function takes an object as an argument and returns the number of references to it. Here is an example. It will track the number of references to two objects, cleverly named
"value_2". First, it displays the number of references to each object before either are assigned to a variable.
Python has to know where it is so it can be bound to something else as the program runs. Second, it’s being used as an argument to this function call, so there’s a reference. And it’s used in the parameter variable inside
Become a Member to join the conversation.