我试图编写一个测试,检查保存类的绑定方法的变量是否与该方法的另一个引用相同.通常这不是问题,但在同一类的另一个方法中完成时似乎不起作用.这是一个最小的例子:
class TestClass:
def sample_method(self):
pass
def test_method(self, method_reference):
print(method_reference is self.sample_method)
Run Code Online (Sandbox Code Playgroud)
我真的使用的是assert代替print,但是既不是在这里也不是在那里,因为最终的结果是相同的.测试运行如下:
instance = TestClass()
instance.test_method(instance.sample_method)
Run Code Online (Sandbox Code Playgroud)
结果是False即使我期待它True.这个问题在Python 3.5和Python 2.7(在Anaconda下运行)中体现出来.
我知道绑定方法是通过执行类似操作获得的闭包TestClass.test_method.__get__(instance, type(instance)).不过,我希望这self.sample_method已经是这样一个封闭的引用,使self.sample_method和instance.sample_method代表相同的参考.
令我困惑的部分原因是pytest我正在运行的真实测试的输出(处理公关matplotlib):
assert <bound method TestTransformFormatter.transform1 of <matplotlib.tests.test_ticker.TestTransformFormatter object at 0x7f0101077b70>> is <bound method TestTransformFormatter.transform1 of <matplotlib.tests.test_ticker.TestTransformFormatter object at 0x7f0101077b70>>
E + where <bound method TestTransformFormatter.transform1 of <matplotlib.tests.test_ticker.TestTransformFormatter object at 0x7f0101077b70>> = <matplotlib.ticker.TransformFormatter object at 0x7f0101077e10>.transform
E + and …Run Code Online (Sandbox Code Playgroud) python ×1