The same memory location is being used by Python for methods a.f
and a.g
, which are **two objects with non-overlapping lifetimes*, so id
returns same identity for both of them. See more detailed explanations below.
From the documentation for the is operator:
The operators is and is not test for object identity: x is y is true
if and only if x and y are the same object.
From the documentation for the is id
Return the “identity” of an object. This is an integer (or long
integer) which is guaranteed to be unique and constant for this object
during its lifetime. Two objects with non-overlapping lifetimes may
have the same id() value.
Explanations:
Whenever you look up a method via class.name
or instance.name
, the method object is created a-new. Python uses the descriptor protocol to wrap the function in a method object each time.
So, when you look up id(a.f)
or id(a.g)
, a new method object is created.
- When you grubbing id of
a.f
, a copy of it is created in memory. This memory location is returned by id
.
- Since there are no references to the newly created method, it reclaimed by the GC (now memory address is available again).
- After you getting id of
a.g
, a copy of it is created at the same memory address, which you retrieve using id
again.
- You've got truthy id's comparison.
Good luck!