a == b为假,但id(a)== id(b)为真? [英] a == b is false, but id(a) == id(b) is true?

查看:123
本文介绍了a == b为假,但id(a)== id(b)为真?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

运行以下内容:

>>> class A:
...     def __str__(self):
...             return "some A()"
... 
>>> class B(A):
...     def __str__(self):
...             return "some B()"
... 
>>> print A()
some A()
>>> print B()
some B()
>>> A.__str__ == B.__str__
False # seems reasonable, since each method is an object
>>> id(A.__str__)==id(B.__str__)
True # what?!

这是怎么回事?

推荐答案

在评估字符串id(A.__str__) == id(B.__str__)时,将创建A.__str__,并获取其ID,然后进行垃圾回收.然后创建了B.__str__,恰好以与A.__str__之前的地址完全相同的地址结束,因此(在CPython中)获得了相同的ID.

As the string id(A.__str__) == id(B.__str__) is evaluated, A.__str__ is created, its id taken, and then garbage collected. Then B.__str__ is created, and happens to end up at the exact same address that A.__str__ was at earlier, so it gets (in CPython) the same id.

尝试将A.__str__B.__str__分配给临时变量,您会看到一些不同的地方:

Try assigning A.__str__ and B.__str__ to temporary variables and you'll see something different:

>>> f = A.__str__
>>> g = B.__str__
>>> id(f) == id(g)
False

有关此现象的更简单示例,请尝试:

For a simpler example of this phenomenon, try:

>>> id(float('3.0')) == id(float('4.0'))
True

这篇关于a == b为假,但id(a)== id(b)为真?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆