- Trending Categories
- Data Structure
- Operating System
- C Programming
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
How to overload Python comparison operators?
Python has magic methods to define overloaded behaviour of operators. The comparison operators (<, <=, >, >=, == and !=) can be overloaded by providing definition to __lt__, __le__, __gt__, __ge__, __eq__ and __ne__ magic methods.
Following program overloads == and >= operators to compare objects of distance class.
class distance: def __init__(self, x=5,y=5): self.ft=x self.inch=y def __eq__(self, other): if self.ft==other.ft and self.inch==other.inch: return "both objects are equal" else: return "both objects are not equal" def __ge__(self, other): in1=self.ft*12+self.inch in2=other.ft*12+other.inch if in1>=in2: return "first object greater than or equal to other" else: return "first object smaller than other" d1=distance(5,5) d2=distance() print (d1==d2) d3=distance() d4=distance(6,10) print (d1==d2) d5=distance(3,11) d6=distance() print(d5>=d6)
Result of above program shows overloaded use of == and >= comparison operators
both objects are equal both objects are equal first object smaller than other
- Python Comparison Operators
- Chaining comparison operators in Python
- Chaining comparison operators in C#
- How to overload python ternary operator?
- Relational and comparison operators in C++
- What is the overload ability of operators in C#
- Explain different comparison operators used in SQL queries
- How can we overload a Python function?
- What is the use of comparison operators with MySQL subquery?
- How does tuple comparison work in Python?
- Python Arithmetic Operators
- Python Assignment Operators
- Python Bitwise Operators
- Python Logical Operators