Passing by reference when assigning values to variables
In the Python language, objects are passed by reference. When assigning a value, whether the object is newly created or already exists, the reference (not the value) of the object is assigned to the variable.
To keep track of objects in memory, Python uses a simple technique called reference counting. In other words, Python internally records how many references each object in use has. An internal tracking variable, called a reference counter. How many references each object has, referred to as reference counting. When an object is created, a reference count is created, and when the object is no longer needed, that is, when the object's reference count becomes 0, it is garbage collected.
When an object is created and assigned (a reference to it) to a variable, the object's reference count is set to 1. When the same object (reference) is assigned to another variable, or is passed as a parameter to a function, method or class instance, or is assigned as a member of a window object, a new reference to the object, or As an alias, it is created (the reference count of the object is automatically increased by 1).
When a reference to an object is destroyed, the reference count is decremented. The most obvious example is when a reference leaves its scope, which most often occurs at the end of a function, all local variables are automatically destroyed, and the object's reference count is decremented. When a variable is assigned to another object, the reference count of the original object is automatically decremented by 1. Other ways to cause an object's reference count to decrease include using the del statement to delete a variable, or when an object is moved out of a window object (or when the reference count of the container object itself becomes 0).
In the above example, a = 1 makes variable a point to integer object 1, b = a makes variable b also points to integer object 1, through the statement id(a), id(b) can see that the memory address pointed to by variable a and variable b is the same. The statement a = 2 assigns the new object 2 to the variable a. At this time, the variable a points to the object 2, and the variable b still points to the original object 1. Through the statements id(a) and id(b), you can see that the memory addresses pointed to by variables a and b are different.
The above is the detailed content of How to use reference to change a variable in python. For more information, please follow other related articles on the PHP Chinese website!