>>> class GridPoint:
def __init__(self, x, y):
self.x = x
self.y = y
def __add__(self, other):
return GridPoint(self.x + other.x, self.y + other.y)
def __str__(self):
string = str(self.x)
string = string + ", " + str(self.y)
return string
>>> point1 = GridPoint(18, 25)
>>> point2 = GridPoint(-7, 13)
>>> point3 = point1 + point2
>>> print(point3)
11, 38
>>>
Operator | Description | Method |
---|---|---|
+ | Addition | __add__(self, other) |
– | Subtraction | __sub__(self, other) |
* | Multiplication | __mul__(self, other) |
/ | True Division | __truediv__(self, other) |
// | Floor Division | __floordiv__(self, other) |
% | Remainder | __mod__(self, other) |
** | Power | __pow__(self, other) |
& | Bitwise AND | __and__(self, other) |
| | Bitwise OR | __or__(self, other) |
^ | Bitwise XOR | __xor__(self, other) |
~ | Bitwise NOT | __not__(self, other) |
Relational operators are overloaded in a very similar way in python. But the difference is, those operators often return true/false instead of another instance of the object. Let’s work with an example..
>>> class My_Sample:
def __init__(self, x, y):
self.x = x
self.y = y
def __gt__(self, other):
return self.x > other.x
def __str__(self):
string = str(self.x)
string = string + ", " + str(self.y)
return string
>>> point1 = My_Sample(18, 25)
>>> point2 = My_Sample(-7, 13)
>>> if point1 > point2:
print('point1 is greater than point2')
else:
print('point1 is not greater than point2')
point1 is greater than point2
>>>
The conventional ‘>’
operator returns true if the operand in the left side of it is greater than the right one. We are going to use this property to compare two instances of class My_Sample
.
Operator | Description | Method |
---|---|---|
> | Greater than | __gt__(self, other) |
>= | Greater than or equal to | __ge__(self, other) |
< | Less than | __lt__(self, other) |
<= | Less than or equal to | __le__(self, other) |
== | Equal to | __eq__(self, other) |
!= | Not equal to | __ne__(self, other) |