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

前端 未结 3 1001
眼角桃花
眼角桃花 2021-01-04 07:33

Ran into the following:

>>> class A:
...     def __str__(self):
...             return \"some A()\"
... 
>>> class B(A):
...     def __str_         


        
相关标签:
3条回答
  • 2021-01-04 08:03

    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
    
    0 讨论(0)
  • 2021-01-04 08:17

    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
    
    0 讨论(0)
  • 2021-01-04 08:17

    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__
    
    0 讨论(0)
提交回复
热议问题