Python unable to compare bound method to itself

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

提交回复
热议问题