1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62
| >>> class Collector(list):
... def __call__(self, init):
... def newInit(itself, *args, **kwargs):
... init(itself, *args, **kwargs)
... self.append(itself)
...
... return newInit
...
... def query(self, **params):
... result = []
...
... for item in self:
... if Collector.match(item, params):
... result.append(item)
...
... return result
...
... @staticmethod
... def match(object, params):
... for attr in params:
... try:
... if getattr(object, attr) != params[attr]:
... return False
...
... except AttributeError:
... return False
...
... return True
...
>>> collector = Collector()
>>> class MyClass(object):
... @collector
... def __init__(self, name, value):
... self.__name = name
... self.__value = value
...
... @property
... def name(self):
... return self.__name
...
... @property
... def value(self):
... return self.__value
...
>>> MyClass("Hello", 25)
<__main__.MyClass object at 0x0232C7F0>
>>> MyClass("Haha", 25)
<__main__.MyClass object at 0x0232CB90>
>>> MyClass("Hello", 32)
<__main__.MyClass object at 0x0232CCB0>
>>> collector.query(name="Hello")
[<__main__.MyClass object at 0x0232C7F0>, <__main__.MyClass object at 0x0232CCB0
>]
>>> collector.query(name="Hello", value=25)
[<__main__.MyClass object at 0x0232C7F0>]
>>> collector.query(value=25)
[<__main__.MyClass object at 0x0232C7F0>, <__main__.MyClass object at 0x0232CB90
>] |
Partager