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?
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
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
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__
精彩评论