8000 Experimenting with magic methods. · github112017/practice-python@680938b · GitHub
[go: up one dir, main page]

Skip to content

Commit 680938b

Browse files
committed
Experimenting with magic methods.
1 parent 6d9ec78 commit 680938b

File tree

2 files changed

+48
-5
lines changed

2 files changed

+48
-5
lines changed

experiments/deck.py

Lines changed: 11 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -4,26 +4,32 @@
44
Card = collections.namedtuple('Card', ['rank', 'suit'])
55

66

7-
class Deck(object):
7+
class Deck:
88
ranks = [str(i) for i in range(2, 11)] + list('JKQA')
99
suits = 'spades diamonds clubs hearts'.split()
1010

1111
def __init__(self):
12-
self._cards = [Card(rank, suit) for rank in self.ranks
13-
for suit in self.suits]
12+
self._cards = [Card(rank, suit) for suit in self.suits
13+
for rank in self.ranks]
1414

1515
def __len__(self):
1616
return len(self._cards)
1717

1818
def __getitem__(self, position):
1919
return self._cards[position]
2020

21+
def __repr__(self):
22+
return 'Deck()'
23+
2124

2225
def main():
2326
deck = Deck()
2427
# print(len(deck))
25-
print(random.choice(deck))
26-
28+
for __ in range(5):
29+
print(random.choice(deck))
30+
# print(deck[12::13])
31+
# for card in reversed(deck):
32+
# print(card)
2733

2834
if __name__ == "__main__":
2935
main()

experiments/vector.py

Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
1+
from math import hypot
2+
3+
4+
class Vector:
5+
def __init__(self, x=0, y=0):
6+
self.x = x
7+
self.y = y
8+
9+
def __repr__(self):
10+
return "Vector({!r}, {!r})".format(self.x, self.y)
11+
12+
def __abs__(self):
13+
return hypot(self.x, self.y)
14+
15+
def __bool__(self):
16+
return bool(abs(self))
17+
18+
def __add__(self, other):
19+
x = self.x + other.x
20+
y = self.y + other.y
21+
return Vector(x, y)
22+
23+
def __mult__(self, scalar):
24+
return Vector(self.x * scalar, self.y * scalar)
25+
26+
27+
def main():
28+
v1 = Vector(2, 4)
29+
v2 = Vector(2, 1)
30+
31+
print(v1)
32+
print(v2)
33+
# assert (v1 + v2) == Vector(4, 5)
34+
# assert abs( * 3)
35+
36+
if __name__ == "__main__":
37+
main()

0 commit comments

Comments
 (0)
0