问题
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?
回答1:
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
回答2:
The following works:
>>> id(A.__str__.im_func) == id(A.__str__.im_func)
True
>>> id(B.__str__.im_func) == id(A.__str__.im_func)
False
回答3:
For those of us here attracted by your title, to determine whether a method was overridden:
class A:
def __str__(self):
return "some A()"
def strWasOverridden(self):
return A.__str__ != self.__str__
来源:https://stackoverflow.com/questions/2319107/a-b-is-false-but-ida-idb-is-true