newbie looking for help, int reference question

Terry Reedy tjreedy at udel.edu
Tue Jan 14 13:13:15 EST 2003


CC'ed
"jodocus" <johocus at zonnet.nl> wrote in message
news:pan.2003.01.14.19.07.19.38207.2750 at zonnet.nl...
> i am learning python, but at the moment i cannot afford to buy a
book on
> the subject. So i am trying to find all the appropriate information
on the
> web. This proves difficult, so if anyone knows a good (complete)
online
> book/resource about the language, i would like to know. I am looking
for
> more than just a tutorial (these are not hard to find), but rather a
> complete work that describes the details of the language.

The Python Reference Manual and Library Reference Manal together do
this.

> A thing I just ran into and couldn't find in the tutorials i am
using:
>
> >>> i = 10
> >>> j = i
> >>> i is j
> 1
> >>> i += 10
> >>> i
> 20
> >>> j
> 10
>
> it seems that, after adding a value, i has become another object.

'i' is not an object.  It is a name bound to an object (via a
'reference'). The second assignment unbinds it from 10 and rebinds it
to 20.  All assignments do an implicit 'if currently bound, unbind'
before doing the binding requested.

> So i guess the + operator makes a new object,

Here you mean +=.  If the object is immutable, yes.  Otherwise, (ie,
for lists) no.

> does this mean that ints are 'immutable'?

Yes.   Good deduction.  But read the manuals for more.

> How do i make sure that j changes when i does?

If you mean "How do I make sure j is rebound when i is?", you can't.
However, if i and j are bound to the same *mutable* object, then a
change to the object is a change to the object regardless of how you
access it..  Try

i=[10]
j=i
i[0]+=10
j # answer below

> Is this  comparable to the Java distinction between objects and
> primitive types,  where objects are referenced but primitives are
not?

In Python, everything is an object with a reference count.  References
can be named or anonymous (as in list and dict slots).

> As a C/C++ programmer i really like to know whether i am dealing
with
> pointers or not, this makes me feel more sure about the correctness
of the
> code i am writing.

CPython implements references as C pointers.  Human interpreters do
not (unless mentally simulating the linear memory of a computer).  So
take your pick.  You can use your understanding of C/C++ to understand
the computer execution of Python as long as you remember that Python
is not C and, in particular, that its abstract data model is quite
different.

Terry J. Reedy

PS. j == [20]
Note that there is still is a rebinding -- of slot 0 withing the list.






More information about the Python-list mailing list