8.1. Operator About
Operator Overload
Operator Overload is the Pythonic way
Operator Overload allows readable syntax
Operator Overload allows simpler operations
All examples in this chapter uses
dataclasses
for you to focus on the important code, not boilerplate code just to make it workshttps://github.com/python/cpython/blob/main/Grammar/python.gram#L695
8.1.1. Operators
Source: https://github.com/python/cpython/blob/main/Grammar/python.gram#L695
Comparison:
==
,!=
,<=
,<
,>=
,>
,not in
,in
,is not
,is
Bitwise:
|
,^
,&
,<<
,>>
Arithmetic:
+
,-
,*
,/
,//
,%
,@
,**
,~
8.1.2. Recap
>>> a = int(1)
>>> b = int(2)
>>> a + b
3
>>> a = float(1.0)
>>> b = float(2.0)
>>> a + b
3.0
>>> a = str('1')
>>> b = str('2')
>>> a + b
'12'
>>> a = list([1])
>>> b = list([2])
>>> a + b
[1, 2]
>>> a = tuple((1,))
>>> b = tuple((2,))
>>> a + b
(1, 2)
8.1.3. Problem
Class 'Vector' does not define '__add__', so the '+' operator cannot be used on its instances
dataclass
is used to generate__init__()
and__repr__()
dataclass
does not have any influence on addition
>>> class Vector:
... def __init__(self, x, y):
... self.x = x
... self.y = y
...
... def __repr__(self):
... return f'Vector(x={self.x}, y={self.y})'
>>>
>>>
>>> a = Vector(x=1, y=2)
>>> b = Vector(x=2, y=3)
>>> a + b
Traceback (most recent call last):
TypeError: unsupported operand type(s) for +: 'Vector' and 'Vector'
8.1.4. Solution
Implement
__add__()
methodTakes two arguments,
self
andother
Other is another instance of the same class
Returns a new instance of the same class
>>> class Vector:
... def __init__(self, x, y):
... self.x = x
... self.y = y
...
... def __repr__(self):
... return f'Vector(x={self.x}, y={self.y})'
...
... def __add__(self, other):
... new_x = self.x + other.x
... new_y = self.y + other.y
... return Vector(x=new_x, y=new_y)
>>>
>>>
>>> a = Vector(x=1, y=2)
>>> b = Vector(x=2, y=3)
>>> a + b
Vector(x=3, y=5)