Why Don't Methods Exhibit Reference Equality?
In Python, while functions maintain reference equality, methods do not. This disparity stems from the way methods are created.
Method Creation
Unlike functions, method objects are instantiated each time they are accessed. This is because methods are essentially descriptors, which return a method object when their .__get__ method is invoked.
What.__dict__['meth'] # Function (not method) object What.__dict__['meth'].__get__(What(), What) # Method object
Method Equality Testing
In Python 3.8 and later, method equality is determined by comparing the .__self__ and .__func__ attributes. If they refer to the same function and instance, the methods are considered equal. However, prior to 3.8, method equality behavior was inconsistent depending on the implementation of the method.
Implications
This variability in method equality affects several scenarios:
Solution for Testing Function Identity
To test whether methods represent the same underlying function, you can compare their .__func__ attributes:
What().meth.__func__ == What().meth.__func__
The above is the detailed content of Why Do Methods Not Exhibit Reference Equality in Python?. For more information, please follow other related articles on the PHP Chinese website!