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?!
这是怎么回事?
Ran into the following:
>>> 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?!
What's going on here?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
以下作品:
The following works:
对于我们这些被你的标题吸引的人来说,要确定方法是否被覆盖:
For those of us here attracted by your title, to determine whether a method was overridden:
当字符串
id(A.__str__) == id(B.__str__)
被求值时,A.__str__
被创建,它的 id 被获取,然后被垃圾收集。然后创建了 B.__str__ ,并且恰好最终到达了 A.__str__ 之前所在的完全相同的地址,因此它(在 CPython 中)获得了相同的 id。尝试将
A.__str__
和B.__str__
分配给临时变量,您会看到不同的东西:有关此现象的更简单的示例,请尝试:
As the string
id(A.__str__) == id(B.__str__)
is evaluated,A.__str__
is created, its id taken, and then garbage collected. ThenB.__str__
is created, and happens to end up at the exact same address thatA.__str__
was at earlier, so it gets (in CPython) the same id.Try assigning
A.__str__
andB.__str__
to temporary variables and you'll see something different:For a simpler example of this phenomenon, try: