Why Do Methods Not Exhibit Reference Equality in Python?

Barbara Streisand
Release: 2024-10-30 00:00:29
Original
967 people have browsed it

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
Copy after login

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__
Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!