Python unable to compare bound method to itself

后端 未结 2 900
终归单人心
终归单人心 2020-12-20 23:02

I am attempting to write a test that checks if a variable holding the bound method of a class is the same as another reference to that method. Normally this is not a problem

相关标签:
2条回答
  • 2020-12-21 00:02

    While the accepted answer is in no way incorrect, it seems like it should be noted that methods are bound on attribute lookup. Furthermore, the behavior of unbound methods changes between Python 2.X and Python 3.X.

    class A:
        def method(self):
            pass
    
    a = A()
    print(a.method is a.method) # False
    
    print(A.method is A.method) # Python 3.X: True, Python 2.X: False
    
    0 讨论(0)
  • 2020-12-21 00:08

    They're not the same reference - the objects representing the two methods occupy different locations in memory:

    >>> class TestClass:
    ...     def sample_method(self):
    ...         pass
    ...     def test_method(self, method_reference):
    ...         print(hex(id(method_reference)))
    ...         print(hex(id(self.sample_method)))
    ... 
    >>> instance = TestClass()
    >>> instance.test_method(instance.sample_method)
    0x7fed0cc561c8
    0x7fed0cc4e688
    

    Changing to method_reference == self.sample_method will make the assert pass, though.

    Edit since question was expanded: seems like a flawed test - probably the actual functionality of the code does not require the references to be the same (is), just equal (==). So your change probably didn't break anything except for the test.

    0 讨论(0)
提交回复
热议问题