Skip to content

Commit 84684a5

Browse files
author
boraxpr
committed
bite 230 - Operator overloading - Object Oriented
1 parent 37b5c22 commit 84684a5

File tree

3 files changed

+64
-0
lines changed

3 files changed

+64
-0
lines changed

.gitignore

+1
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
1+
*.md
12
*.txt
23
*.html
34
.idea/

230/test_thumbs.py

+41
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,41 @@
1+
import pytest
2+
3+
from thumbs import Thumbs
4+
5+
6+
@pytest.fixture(scope="module")
7+
def thumbs():
8+
return Thumbs()
9+
10+
11+
@pytest.mark.parametrize("arg, expected", [
12+
(-10, "👎 (10x)"),
13+
(-9, "👎 (9x)"),
14+
(-8, "👎 (8x)"),
15+
(-7, "👎 (7x)"),
16+
(-6, "👎 (6x)"),
17+
(-5, "👎 (5x)"),
18+
(-4, "👎 (4x)"),
19+
(-3, "👎👎👎"),
20+
(-2, "👎👎"),
21+
(-1, "👎"),
22+
(1, "👍"),
23+
(2, "👍👍"),
24+
(3, "👍👍👍"),
25+
(4, "👍 (4x)"),
26+
(5, "👍 (5x)"),
27+
(6, "👍 (6x)"),
28+
(7, "👍 (7x)"),
29+
(8, "👍 (8x)"),
30+
(9, "👍 (9x)"),
31+
(10, "👍 (10x)"),
32+
])
33+
def test_operator_overloading_works_both_ways(arg, expected, thumbs):
34+
assert thumbs * arg == arg * thumbs == expected
35+
36+
37+
def test_exception(thumbs):
38+
with pytest.raises(ValueError):
39+
thumbs * 0
40+
with pytest.raises(ValueError):
41+
0 * thumbs

230/thumbs.py

+22
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
THUMBS_UP, THUMBS_DOWN = '👍', '👎'
2+
3+
4+
def emoji_multiply(multiplier):
5+
if multiplier == 0:
6+
raise ValueError("Specify a number")
7+
thumb = THUMBS_UP
8+
if multiplier < 0:
9+
thumb = THUMBS_DOWN
10+
multiplier = abs(multiplier)
11+
if multiplier in [1, 2, 3]:
12+
return thumb * multiplier
13+
else:
14+
return str(thumb) + " ({}x)".format(multiplier)
15+
16+
17+
class Thumbs:
18+
def __mul__(self, multiplier):
19+
return emoji_multiply(multiplier)
20+
21+
def __rmul__(self, multiplier):
22+
return emoji_multiply(multiplier)

0 commit comments

Comments
 (0)