>> class B(A)-6ren">
gpt4 book ai didi

python - a == b 为假,但 id(a) == id(b) 为真?

转载 作者:太空狗 更新时间:2023-10-29 17:28:29 24 4
gpt4 key购买 nike

遇到以下情况:

>>> 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。

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

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

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

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

关于python - a == b 为假,但 id(a) == id(b) 为真?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2319107/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com