Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
How to implement Python __lt__ __gt__ custom (overloaded) 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 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 __lt__(self, other):
in1=self.ft*12+self.inch
in2=other.ft*12+other.inch
if in1d2)
d3=distance()
d4=distance(6,10)
print (d1Result shows implementation of __lt__ and _gt__ magic methods
first object not greater than other
first object not smaller than other
first object smaller than other
Advertisements
