[Tutor] integers are also objects?
Mon, 3 Dec 2001 00:20:59 -0800 (PST)
On Mon, 3 Dec 2001, Remco Gerlich wrote:
> > So my question is that does "==" work on contents in case of
> integers or it works only on references and python makes sure that
> integer references with same content point to the same location, the
> way it works for strings.
> Not all strings with the same content point to the same location; some of
> them are cached, but not all of them. Typically only strings that you use as
> literals (the ones you "spell out" in program code) are cached, not strings
> that are the result of a computation.
And if we do want computed string to be cached, we can use the
>>> s = "hello world"
>>> s2 = "hello" + " world"
>>> s = intern(s)
>>> s2 = intern(s2)
> Any == check on any two objects first compares the two references, if
> they're the same then the objects are equal (since they're the same
> object). Only if they're not the same, are the objects then compared
> for value.
If we do want to check to see if two things refer to the same object, we
can use ths 'is' operator:
>>> 1 + 1 is 2
1 ## ... but this works just because of the
## caching behavior of small integers.
>>> 1 + 1 == 2
>>> 101 + 1 is 102 ## Let's try this on larger numbers
>>> 101 + 1 == 102