What are the meanings and differences between "needs" and "re-assignments" of a variable?

From Python in a nutshell:

Save global

Never use a global if the function body just uses a global variable (including changing the object, the associated variable when the object is modified).

Use the global operator only if the function body is restoring a global variable (usually by assigning a variable name).

What are the meanings and differences between "uses" and "rebinds" of a variable?

Is the "mutating object bound to a variable" "uses" or "rechecks" the variable? Why?

+3


source to share


2 answers


"Mutate" and "bind" / "rebind" are two mutually exclusive operations. Mutating changes the object, and the binding changes the name.

This is the binding:

a = []

      



This mutates:

a.append(None)

      

"Usage" means access to an existing object associated with a name, for reading or for mutation.

+2


source


Using a variable

When you use a variable, you use the actual value of the variable - the object to which it refers, or the mutating object to which the variable name refers.Here is an example:

>>> var1 = 1
>>> var2 = [1]
>>> 
>>> def func():
    print(var1)
    var2.append(2)


>>> func()
1
>>> var2
[1, 2]
>>> 

      

In the above example, we are using var1

and var2

internally func

. We use var1

because we are using this value in our call print

. And we used var2

because we mutated the object it was referring to. Please note that we did not change the referenced object var2

, we used an existing object and modified it. Also note that we never tried to assign a new value to any variable.

Variable permutation



When you reformat a variable, you change the object that the variable name refers to . Here's another example to help illustrate the point:

>>> var1 = 1
>>> 
>>> def func():
    global var1
    var1 = 2


>>> func()
>>> var1
2
>>>

      

In the examples above. We will weave var

inside func

. var1

use an object reference 1

, but since we are binding var1

in 2

, it now refers to an object 2

.

So what's the difference?

The difference is that when we use a variable, we just use the object that the variable already refers to. When we recheck a variable, we change the object that the variable belongs to.

+1


source







All Articles