[Edu-sig] looking for explanations... globals dynamic dict

Carl Cerecke carl at free.org.nz
Mon Mar 28 22:59:40 CEST 2011


On 29 March 2011 08:28, Massimo Di Pierro <mdipierro at cs.depaul.edu> wrote:

>
> primitive types like integers behave differently
>
> >>> a = 1
> >>> b = a  # b and a are two different 1s
> >>> b+=2
> >>> print a
> 1
>
>
>
Well, not really. Although I see what you are trying to say.

numbers (like strings) are immutable. There can ever be only one number 1.
You can't change a number to something else. If add 5 to 3, the number 3
doesn't change, I get a new number, 8.

with "a = 1", python is still using a reference to an object. You can see
this because ints have methods:
>>> a = 1
>>> a.__add__
<method-wrapper '__add__' of int object at 0x009ADD38>
>>> a.__add__(5)
6
>>> a
1


After a 'b = a' statement, b and a point to the same object (in this case,
the one at 0x009ADD38):

>>> b = a
>>> b.__add__
<method-wrapper '__add__' of int object at 0x009ADD38>
>>>

Remember,  the object that both b and a reference is immutable. It's the
number 1. You can't change the number one to be some other number. If you
then do 'b += 2', python calculates the result of the expression 'b + 2',
which is 3, and then changes b's reference to point to the object
representing the int 3.

Cheers,
Carl.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/edu-sig/attachments/20110329/276cec74/attachment.html>


More information about the Edu-sig mailing list