Python unable to compare bound method to itself

后端 未结 2 913
终归单人心
终归单人心 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: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.

提交回复
热议问题