Skip to content

Commit 475339e

Browse files
Flyweight example
1 parent f378925 commit 475339e

File tree

1 file changed

+46
-0
lines changed

1 file changed

+46
-0
lines changed

18_Wstep_do_obiektowosci/flyweight.py

+46
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,46 @@
1+
from weakref import WeakValueDictionary
2+
3+
4+
class flyweight:
5+
def __init__(self, cls):
6+
self._cls = cls
7+
self._instances = WeakValueDictionary()
8+
9+
def __call__(self, *args, **kargs):
10+
return self._instances.setdefault(
11+
(args, tuple(kargs.items())),
12+
self._cls(*args, **kargs))
13+
14+
15+
@flyweight
16+
class Card:
17+
values = ('2', '3', '4', '5', '6', '7', '8', '9', '10', 'J', 'Q', 'K', 'A')
18+
suits = ('clubs', 'diamonds', 'hearts', 'spades')
19+
20+
def __init__(self, value='A', suit='spade'):
21+
self.value, self.suit = value, suit
22+
print(f"In init; value is {value}; suit is {suit}")
23+
24+
def __repr__(self):
25+
return "Card('%s','%s')" % (self.value, self.suit)
26+
27+
def __eq__(self, card):
28+
return self.value == card.value and self.suit == card.suit
29+
30+
def czy_bije(self, other):
31+
if self.suit == other.suit:
32+
if self.values.index(self.value) > self.values.index(other.value):
33+
return True
34+
return False
35+
36+
def __gt__(self, n):
37+
return self.czy_bije(n)
38+
39+
def __lt__(self, card):
40+
return card.czy_bije(self)
41+
42+
43+
krol_karo1 = Card('K', 'diamonds')
44+
krol_karo2 = Card('K', 'diamonds')
45+
46+
krol_karo1 is krol_karo2

0 commit comments

Comments
 (0)