sexta-feira, 23 de agosto de 2013

Python - Variables

Other languages have "variables"

In many other languages, assigning to a variable puts a value into a box.
int a = 1;
a1box.png
Box "a" now contains an integer 1.
Assigning another value to the same variable replaces the contents of the box:
a = 2;
a2box.png
Now box "a" contains an integer 2.
Assigning one variable to another makes a copy of the value and puts it in the new box:
int b = a;
b2box.pnga2box.png
"b" is a second box, with a copy of integer 2. Box "a" has a separate copy.

Python has "names"

In Python, a "name" or "identifier" is like a parcel tag (or nametag) attached to an object.
a = 1
a1tag.png
Here, an integer 1 object has a tag labelled "a".
If we reassign to "a", we just move the tag to another object:
a = 2
a2tag.png1.png
Now the name "a" is attached to an integer 2 object.
The original integer 1 object no longer has a tag "a". It may live on, but we can't get to it through the name "a". (When an object has no more references or tags, it is removed from memory.)
If we assign one name to another, we're just attaching another nametag to an existing object:
b = a
ab2tag.png
The name "b" is just a second tag bound to the same object as "a".
Although we commonly refer to "variables" even in Python (because it's common terminology), we really mean "names" or "identifiers". In Python, "variables" are nametags for values, not labelled boxes.
If you get nothing else out of this tutorial, I hope you understand how Python names work. A good understanding is certain to pay dividends, helping you to avoid cases like this:

Sem comentários:

Enviar um comentário