它们不是相同的引用-表示两种方法的对象在内存中的位置不同:
>>> 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
更改为method_reference == self.sample_method
将使断言通过。
自问题扩展以来的编辑:似乎是一个有缺陷的测试- 代码的实际功能可能不需要引用相同(is
),而是相等(==
)。因此,除了测试之外,您所做的更改可能不会破坏任何其他内容。