Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
311 views
in Technique[技术] by (71.8m points)

python - a == b is false, but id(a) == id(b) is true?

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...