1

How can this be possible in Python 3? k1 and k2's a attributes refer to the same memory location in IPython console

class K():

    def __init__(self, a):
        self.a = a


k1 = K(4)
k2 = K(4)

hex(id(k1)) # 0x10d77b668
hex(id(k2)) # 0x10d77b6a0

hex(id(k1.a)) # 0x10d41caa0
hex(id(k2.a)) # 0x10d41cac0

id(k1.a) == id(k2.a) # True

I am mostly concerned about the object reference issue going on here rather than the 'is' operator test, which I believe is not the problem I am trying to solve. Because, both k1.a and k2.a would pass the is test because the two references refer to the same object. But what I would like to know is, why that happens.

c00der
  • 543
  • 1
  • 4
  • 20
  • 2
    Both `a` attributes refer to an integer with the value 4, and small integer objects (-5 thru 256, I think) are cached for efficiency. If this makes any difference to your program, then your program is broken. – jasonharper Feb 26 '18 at 16:54
  • Interesting, didn't know that happens. It is only a test. Nothing critical. Looks like your theory is correct. When the number is big, they are different. Is there any way to change this behavior? – c00der Feb 26 '18 at 17:03
  • 1
    That is not @jasonharper's "theory" that is a documented part of the CPython implementation: https://docs.python.org/3/c-api/long.html#c.PyLong_FromLong – juanpa.arrivillaga Feb 26 '18 at 17:41
  • @c00der also, just so you know, instance variables, in general, won't have different `id` unless they are different objects, But if you did `some_object = object()` and then `k1 = K(some_object); k2 = K(some_obejct)`, then of course, `id(k1.a) == id(k2.a)` – juanpa.arrivillaga Feb 26 '18 at 18:09
  • @juanpa.arrivillaga, thanks, yeah, I can see why that happens. There you reference the same object. – c00der Feb 26 '18 at 18:57

0 Answers0