7.7. Operator Left

  • x + y - will call method "add" on object x (x.__add__(y))

  • x - y - will call method "sub" on object x (x.__sub__(y))

  • x * y - will call method "mul" on object x (x.__mul__(y))

  • x ** y - will call method "pow" on object x (x.__pow__(y))

  • x @ y - will call method "matmul" on object x (x.__matmul__(y))

  • x / y - will call method "truediv" on object x (x.__truediv__(y))

  • x // y - will call method "floordiv" on object x (x.__floordiv__(y))

  • x % y - will call method "mod" on object x (x.__mod__(y))

Table 7.2. Numerical Operator Overload

Operator

Method

obj + other

obj.__add__(other)

obj - other

obj.__sub__(other)

obj * other

obj.__mul__(other)

obj ** other

obj.__pow__(other)

obj @ other

obj.__matmul__(other)

obj / other

obj.__truediv__(other)

obj // other

obj.__floordiv__(other)

obj % other

obj.__mod__(other)

7.7.1. Memory

  • tuple is immutable

  • list is mutable

  • tuple + tuple will generate new tuple

  • list + list will generate new list

  • __add__() operator on tuple is the same as on list

>>> a = [1, 2, 3]
>>> id(a)  
4354839104
>>>
>>> a = a + [4, 5, 6]
>>> id(a)  
4358229056
>>>
>>> a
[1, 2, 3, 4, 5, 6]
>>> a = (1, 2, 3)
>>> id(a)  
4359020416
>>>
>>> a = a + (4, 5, 6)
>>> id(a)  
4360038688
>>>
>>> a
(1, 2, 3, 4, 5, 6)

7.7.2. Example

>>> from dataclasses import dataclass
>>>
>>> @dataclass
... class Vector:
...     x: int
...     y: int
...
...     def __add__(self, other):
...         new_x = self.x + other.x
...         new_y = self.y + other.y
...         return Vector(new_x, new_y)
>>>
>>>
>>> a = Vector(x=1, y=2)
>>> b = Vector(x=3, y=4)
>>> c = Vector(x=5, y=6)
>>>
>>> (a+b) + c
Vector(x=9, y=12)

7.7.3. Use Case - 0x01

>>> hero @ Position(x=50, y=120)  

7.7.4. Assignments

Code 7.25. Solution
"""
* Assignment: Operator Left Matmul
* Complexity: easy
* Lines of code: 3 lines
* Time: 3 min

English:
    1. Make object understand following call: `position @ (1, 2)`
    1. Overload `@` operator, to take `tuple[int, int]` as argument
    2. Set `x` and `y` coordinates based on passed values
    3. Run doctests - all must succeed

Polish:
    1. Spraw aby obiekt obsługiwał to wywołanie: `position @ (1, 2)`
    1. Przeciąż operator `@`, aby przyjmował `tuple[int, int]` jako argument
    2. Zmień koordynaty `x` i `y` na podstawie przekazanych wartości
    3. Uruchom doctesty - wszystkie muszą się powieść

Hints:
    * `object.__matmul__()`

Tests:
    >>> import sys; sys.tracebacklimit = 0

    >>> position = Position()
    >>> position
    Position(x=0, y=0)
    >>> position @ (1, 2)
    >>> position
    Position(x=1, y=2)
"""

from dataclasses import dataclass


@dataclass
class Position:
    x: int = 0
    y: int = 0