您好, 欢迎来到 !    登录 | 注册 | | 设为首页 | 收藏本站

Python无法将绑定方法与其自身进行比较

Python无法将绑定方法与其自身进行比较

它们不是相同的引用-表示两种方法的对象在内存中的位置不同:

>>> 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),而是相等(==)。因此,除了测试之外,您所做的更改可能不会破坏任何其他内容

python 2022/1/1 18:35:18 有404人围观

撰写回答


你尚未登录,登录后可以

和开发者交流问题的细节

关注并接收问题和回答的更新提醒

参与内容的编辑和改进,让解决方法与时俱进

请先登录

推荐问题


联系我
置顶