Skip to content

Commit e2a05f6

Browse files
committed
Update of flyweight pattern
1 parent 6993592 commit e2a05f6

File tree

1 file changed

+13
-5
lines changed

1 file changed

+13
-5
lines changed

flyweight.py

Lines changed: 13 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -14,7 +14,7 @@ class Card(object):
1414
"""Flyweight implementation. If the object exists in the
1515
pool just return it (instead of creating a new one)"""
1616
def __new__(cls, value, suit):
17-
obj = Card._CardPool.get(value + suit, None)
17+
obj = Card._CardPool.get(value + suit)
1818
if not obj:
1919
obj = object.__new__(cls)
2020
Card._CardPool[value + suit] = obj
@@ -27,16 +27,24 @@ def __new__(cls, value, suit):
2727
def __repr__(self):
2828
return "<Card: %s%s>" % (self.value, self.suit)
2929

30-
3130
if __name__ == '__main__':
3231
# comment __new__ and uncomment __init__ to see the difference
3332
c1 = Card('9', 'h')
3433
c2 = Card('9', 'h')
3534
print(c1, c2)
36-
print(c1 == c2)
35+
print(c1 == c2, c1 is c2)
3736
print(id(c1), id(c2))
3837

38+
c1.temp = None
39+
c3 = Card('9', 'h')
40+
print(hasattr(c3, 'temp'))
41+
c1 = c2 = c3 = None
42+
c3 = Card('9', 'h')
43+
print(hasattr(c3, 'temp'))
44+
3945
### OUTPUT ###
40-
# <Card: 9h> <Card: 9h>
46+
# (<Card: 9h>, <Card: 9h>)
47+
# (True, True)
48+
# (31903856, 31903856)
4149
# True
42-
# 140368617673296 140368617673296
50+
# False

0 commit comments

Comments
 (0)