Previously I had thought that doing a=110 creates an object 'a' that stores the value 110 (and when we do b=a, b simply points to a). I had no idea there is a third object in play.
Previously I had thought that doing a=110 creates an object 'a' that stores the value 110 (and when we do b=a, b simply points to a). I had no idea there is a third object in play.
Which means that, if you execute "a = 110" a bunch of times, no new objects get created. If you execute "a= 110+300" a bunch of times, a whole bunch of new objects is created and destroyed.
By the way, this boxing/unboxing logic is also at work when you stick numbers into a standard HashMap, since it stores Integer objects and not the primitive type. However, in Java you can use GNU Trove's IntObjectHashMap or ObjectIntHashMap and save some memory, whereas Python's "everything is an object" rules this out (unless you're using PyPy and its tracing jit which figures out that a always contains a number).
That's not to say that OO is necessarily the ideal language paradigm, but it has certainly been the most dominant in the era Python has existed.
EDIT: And here's Guido explaining why he didn't want that in Python: https://mail.python.org/pipermail/python-dev/2004-July/04614...
This is why JIT runtimes need a "warm up time" to get really fast, say V8 for JavaScript.
http://www.laurentluce.com/posts/python-integer-objects-impl...
>>> a = 110
>>> b = 110
>>> id(a) == id(b)
TrueThat's a sticking point with a lot of young Java programmers encountering boxed types for the first time. They see that x is true here:
Integer x = new Integer(5);
Integer y = new Integer(5);
x == y
But this is false: Integer x = new Integer(5000);
Integer y = new Integer(5000);
x == y
(The real fix, of course, is to use the 'equals' method when comparing objects.)The true problem is that newbies who haven't grasped the difference see that x==y in a sample program and then leap to all sorts of conclusions, overgeneralizing what they observed because they don't understand how it happened.
Compare Ruby:
1 == 1 => true
4711 == 4711 => true
1.object_id == 1.object_id => true
4711.object_id == 4711.object_id => falseRuby's default #== for new classes simply performs identity comparison, just like in Java. The difference is that Ruby has operator overloading, so all the builtin classes overload it with something sensible.
(This could work in Java, or it could go the .NET route and ban using the == operator entirely until a certain interface (.NET's IEquatable) is fulfilled.)