Why The Id Of An Object Would Change Depending On The Line In The Python Shell
This questions is just out of curiosity. While I was reading the python's object model documentation, I decided to experiment a little with the id of a class method and found this
Solution 1:
I will explain wat the line id(A().a)
does:
A() # creates a new objectI call a
Then
A().a # creates a function f bound toaA.a.__get__(A(), A) # same as above
>>> A.a.__get__(A(), A)
<bound method A.a of <__main__.Aobject at 0x02D85550>>
>>> A().a
<bound method A.a of <__main__.Aobject at 0x02D29410>>
This bound function is always another because it has another object in __self__
>>>a = A()>>>assert a.a.__self__ is a
__self__
will be passed as first argument self
to the function A.a
EDIT: This is what it looks like:
Python 3.3.0 (v3.3.0:bd8afb90ebf2, Sep 292012, 10:55:48) [MSC v.160032 bit (Intel)] on win32
Type"copyright", "credits"or"license()"for more information.
>>> classA:
defa(self):
pass>>> id(A().a)
43476312>>> id(A().a)
49018760
Here the id repeats like abab
Python 3.2.2 (default, Sep 42011, 09:51:08) [MSC v.150032 bit (Intel)] on win32
Type"copyright", "credits"or"license()"for more information.
>>> classA:
defa(self):
pas
s
>>> id(A().a)
50195512>>> id(A().a)
50195832>>> id(A().a)
50195512>>> id(A().a)
50195832
EDIT: For linux or what is not my machine and whatsoever I do not know
id(A().a)
will always give the same result except if you store this to a variable. I do not know why but I would think that it is because of performance optimization. For objects on the stack you do not need to allocate new space for an object every time you call a function.
Post a Comment for "Why The Id Of An Object Would Change Depending On The Line In The Python Shell"