简体   繁体   中英

Can someone explain this behavior in Python?

Consider the following interaction:

>>> def func():
...  pass
...
>>> id(func)
2138387939184
>>> def func():
...   x =  5
...
>>> id(func)
2138390016064
>>> def func():
...  pass
...
>>> id(func)
2138387939184
>>>
>>> def func2():
...  pass
...
>>> id(func2)
2138390016064

So you can see that after func is redefined to its original form: pass , it received the same memory address. That got me thinking that when I define another function, no matter its name, if the body (and parameters list) are the same, it will be bound to the same address as well, but when I define func2 as only pass , it gets another address.

Can someone explain this?

EDIT

My assumption was that the reason that when I defined

...
def func():
  pass

in the second time it received the same id, was that this function definition already exists in that memory address, so the interpreter doesn't have to recreate it. But given the following:

>>> def func():
...  pass
...
>>> id(func)
1829442649968
>>> def func():
...   x = 5
...
>>> id(func)
1829448396864
>>> def func():
...   y = 10
...
>>> id(func)
1829442649968

clearly shows that this thesis was wrong. It assigned the func object the same id only because it is now free.

cf the documentation for the builtin id function :

Return the “identity” of an object. This is an 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.

You SHOULD not consider valid the id of objects that have been deleted.

Because you redefine your function func , you actually create a new object (functions are objects in Python) each time, that's why the id changed in the first place (because it is a new, different object, with a different id). That the same id was reused later is coincidental, it may or not happen, and it tells you nothing useful (except for garbage collection implementation details).

Comparing ids is safer when performed at the same time, for example if id(obj1) == id(obj2): print("we are sure it is the same object") .

See also this very similar question: Why is the id of a Python class not unique when called quickly?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM