6.7. Operator Left¶
x + y
- will call method "add" on objectx
(x.__add__(y)
)x - y
- will call method "sub" on objectx
(x.__sub__(y)
)x * y
- will call method "mul" on objectx
(x.__mul__(y)
)x ** y
- will call method "pow" on objectx
(x.__pow__(y)
)x @ y
- will call method "matmul" on objectx
(x.__matmul__(y)
)x / y
- will call method "truediv" on objectx
(x.__truediv__(y)
)x // y
- will call method "floordiv" on objectx
(x.__floordiv__(y)
)x % y
- will call method "mod" on objectx
(x.__mod__(y)
)
Operator |
Method |
---|---|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
6.7.1. Memory¶
tuple
is immutablelist
is mutabletuple + tuple
will generate newtuple
list + list
will generate newlist
__add__()
operator ontuple
is the same as onlist
>>> 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)
6.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)
6.7.3. Use Case - 0x01¶
>>> hero @ Position(x=50, y=120)
6.7.4. Use Case - 0x02¶
>>> hero['gold'] += dragon['gold']
6.7.5. Assignments¶
"""
* 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