Get the App
SLTechnology News&Howtos  ›  Development  › 

A simple method of how to implement comparison operators in python

Shulou Source: shulou.com Published: 2022-06-01 05:48:45 10月02日 Update

Xiaobian to share with you how to achieve the comparison operator python simple method, I believe that most people do not understand, so share this article for your reference, I hope you will learn a lot after reading this article, let's go to understand it!

A simple way to implement comparison operators

It is tedious to implement all the comparison operators (such as lt, le, gt, ge) for a class. Is there an easier way to do this? At times like this, "functools.total_ordering" is a good helper:

Novice learning, Python tutorials / tools / methods / troubleshooting + V:itz992from functools import total_ordering @ total_ordering class Number: def _ _ init__ (self, value): self.value = value def _ lt__ (self, other): return self.value

< other.value def __eq__(self, other): return self.value == other.value print(Number(20) >

Number (3)) print (Number (1)

< Number(5)) print(Number(15) >

= Number (15)) print (Number (10)

Tags: Methods operators operations articles content learning minimum tedious less function principle most examples that is tools helpers tutorials beginners time more Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno Shulou Information Linux Huawei Shulou Technology NVidia