|
5 | 5 |
|
6 | 6 | importweakref |
7 | 7 |
|
| 8 | +fromsiximportadd_metaclass |
| 9 | + |
8 | 10 |
|
9 | 11 | classFlyweightMeta(type): |
| 12 | + |
10 | 13 | def__new__(mcs, name, parents, dct): |
11 | 14 | """ |
| 15 | + Set up object pool |
12 | 16 |
|
13 | 17 | :param name: class name |
14 | 18 | :param parents: class parents |
15 | 19 | :param dct: dict: includes class attributes, class methods, |
16 | 20 | static methods, etc |
17 | 21 | :return: new class |
18 | 22 | """ |
19 | | - |
20 | | -# set up instances pool |
21 | 23 | dct['pool'] =weakref.WeakValueDictionary() |
22 | 24 | returnsuper(FlyweightMeta, mcs).__new__(mcs, name, parents, dct) |
23 | 25 |
|
24 | 26 | @staticmethod |
25 | 27 | def_serialize_params(cls, *args, **kwargs): |
26 | | -"""Serialize input parameters to a key. |
| 28 | +""" |
| 29 | + Serialize input parameters to a key. |
27 | 30 | Simple implementation is just to serialize it as a string |
28 | | -
|
29 | 31 | """ |
30 | | -args_list=map(str, args) |
| 32 | +args_list=list(map(str, args)) |
31 | 33 | args_list.extend([str(kwargs), cls.__name__]) |
32 | 34 | key=''.join(args_list) |
33 | 35 | returnkey |
@@ -65,20 +67,15 @@ def __repr__(self): |
65 | 67 | return"<Card: %s%s>"% (self.value, self.suit) |
66 | 68 |
|
67 | 69 |
|
| 70 | +@add_metaclass(FlyweightMeta) |
68 | 71 | classCard2(object): |
69 | | -__metaclass__=FlyweightMeta |
70 | 72 |
|
71 | 73 | def__init__(self, *args, **kwargs): |
72 | 74 | # print('Init{}:{}'.format(self.__class__, (args, kwargs))) |
73 | 75 | pass |
74 | 76 |
|
75 | 77 |
|
76 | 78 | if__name__=='__main__': |
77 | | -importsys |
78 | | -ifsys.version_info[0] >2: |
79 | | -sys.stderr.write("!!! This example is compatible only with Python 2 ATM !!!\n") |
80 | | -raiseSystemExit(0) |
81 | | - |
82 | 79 | # comment __new__ and uncomment __init__ to see the difference |
83 | 80 | c1=Card('9', 'h') |
84 | 81 | c2=Card('9', 'h') |
|
0 commit comments