From e2a05f6cb5f056e7d6f5709acfcc48ff4c6f6c20 Mon Sep 17 00:00:00 2001 From: Mikhail Lyundin Date: Mon, 3 Aug 2015 10:21:06 +0300 Subject: [PATCH] Update of flyweight pattern --- flyweight.py | 18 +++++++++++++----- 1 file changed, 13 insertions(+), 5 deletions(-) diff --git a/flyweight.py b/flyweight.py index efa48981..40c910fd 100644 --- a/flyweight.py +++ b/flyweight.py @@ -14,7 +14,7 @@ class Card(object): """Flyweight implementation. If the object exists in the pool just return it (instead of creating a new one)""" def __new__(cls, value, suit): - obj = Card._CardPool.get(value + suit, None) + obj = Card._CardPool.get(value + suit) if not obj: obj = object.__new__(cls) Card._CardPool[value + suit] = obj @@ -27,16 +27,24 @@ def __new__(cls, value, suit): def __repr__(self): return "" % (self.value, self.suit) - if __name__ == '__main__': # comment __new__ and uncomment __init__ to see the difference c1 = Card('9', 'h') c2 = Card('9', 'h') print(c1, c2) - print(c1 == c2) + print(c1 == c2, c1 is c2) print(id(c1), id(c2)) + c1.temp = None + c3 = Card('9', 'h') + print(hasattr(c3, 'temp')) + c1 = c2 = c3 = None + c3 = Card('9', 'h') + print(hasattr(c3, 'temp')) + ### OUTPUT ### -# +# (, ) +# (True, True) +# (31903856, 31903856) # True -# 140368617673296 140368617673296 +# False