? Deep down, we're all the same *
class WTF: pass
Output:
>>> WTF() == WTF() # 两个不同的对象不相等False>>> WTF() is WTF() # id一样不相等False>>> hash(WTF()) == hash(WTF()) # 哈希值也“应该”不相等True>>> id(WTF()) == id(WTF())True
Explain:
- When
id
a function is used, Python creates an WTF
object named and passes it to the id
function. The id
function gets its id
(its memory location) and discards the object.
- When we do this in the interaction, Python will give the object a new location if it finds an object that occupies an unused memory location.
But why use is
the comparison results False
? Let's take a look.
class WTF(object):def __init__(self): print("I") # 创建时触发def __del__(self): print("D") #丢弃时触发
Output:
>>> WTF() is WTF()I # 创建1I # 创建2,比较,内存位置不同,返回falseD # 删除1D # 删除2False>>> id(WTF()) == id(WTF())I #创建1D #记住内存,连同内存一起删掉I #创建2,它用了1的内存(因为1已经删掉),比较,两个内存相同。D #删除2True
Python a day---difficult to understand the phenomenon + clear explanation---We are all the same