8.4. Operator Logical
not
and
or
xor
invert
neg
pos
8.4.1. SetUp
>>> from dataclasses import dataclass
8.4.2. Example
>>> @dataclass
... class Vector:
... x: int
... y: int
...
... def __and__(self, other): ... # &
... def __or__(self, other): ... # |
... def __xor__(self, other): ... # ^
... def __invert__(self): ... # ~
#%% Use Case - 1
crew1 = {'Mark', 'Melissa', 'Rick'} crew2 = {'Alex', 'Beth', 'Chris'}
# Sumowanie zbiorów (set) result = crew1 | crew2
# Do zbioru crew1 dodajemy elementy z crew2 crew1 |= crew2
#%% Use Case - 2 # od Python 3.9
crew1 = {'botanist':'Mark', 'commander':'Melissa', 'pilot':'Rick'} crew2 = {'chemist':'Alex', 'engineer':'Beth', 'medic':'Chris'}
# Sumowanie dictów result = crew1 | crew2
# Do dict crew1 dodajemy elementy z crew2 crew1 |= crew2
8.4.3. Use Case 0x03
>>> import numpy as np
>>>
>>> a = np.array([[1, 2, 3],
... [4, 5, 6],
... [7, 8, 9]])
>>> (a>5)
array([[False, False, False],
[False, False, True],
[ True, True, True]])
>>> ~(a>5)
array([[ True, True, True],
[ True, True, False],
[False, False, False]])
8.4.4. Use Case 0x04
>>> import numpy as np
>>>
>>> a = np.array([[1, 2, 3],
... [4, 5, 6],
... [7, 8, 9]])
>>> (a>3) & (a<7)
array([[False, False, False],
[ True, True, True],
[False, False, False]])
>>> ((a>3) & (a<7)) | (a%2==0)
array([[False, True, False],
[ True, True, True],
[False, True, False]])
>>> ~(((a>3) & (a<7)) | (a%2==0))
array([[ True, False, True],
[False, False, False],
[ True, False, True]])
>>> a.__gt__(3).__and__(a.__lt__(7)).__or__(a.__mod__(2).__eq__(0)).__invert__()
array([[ True, False, True],
[False, False, False],
[ True, False, True]])