Home  >  Article  >  Backend Development  >  Why Do Methods Not Exhibit Reference Equality in Python?

Why Do Methods Not Exhibit Reference Equality in Python?

Barbara Streisand
Barbara StreisandOriginal
2024-10-30 00:00:291030browse

Why Do Methods Not Exhibit Reference Equality in Python?

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:

  • When using the is operator to check if methods are identical, it returns False unless the methods are bound to the same instance and function.
  • Conversely, == equality testing for methods in Python 3.8 provides expected results by comparing the .__self__ and .__func__ attributes.

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn