| a | b | |
|---|
| 0 | + | # -*- coding: utf-8 -*- |
|---|
| 0 | + | |
|---|
| 0 | + | _instances = {} |
|---|
| 0 | + | |
|---|
| 0 | + | class Wrapper(object): |
|---|
| 0 | + | |
|---|
| 0 | + | def __new__(cls, **kwargs): |
|---|
| 0 | + | instance = object.__new__(cls) |
|---|
| 0 | + | instance.__init__(**kwargs) |
|---|
| 0 | + | if instance.uuid in _instances: |
|---|
| 0 | + | cached = _instances[instance.uuid] |
|---|
| 0 | + | for attr in kwargs.items(): |
|---|
| 0 | + | setattr(cached, *attr) |
|---|
| 0 | + | return cached |
|---|
| 0 | + | else: |
|---|
| 0 | + | _instances[instance.uuid] = instance |
|---|
| 0 | + | return instance |
|---|
| 0 | + | |
|---|
| 0 | + | @property |
|---|
| 0 | + | def uuid(self): |
|---|
| 0 | + | raise NotImplementedError() |
|---|
| 0 | + | |
|---|
| 0 | + | class Test(Wrapper): |
|---|
| 0 | + | |
|---|
| 0 | + | def __init__(self, name=None): |
|---|
| 0 | + | self.name = name |
|---|
| 0 | + | |
|---|
| 0 | + | @property |
|---|
| 0 | + | def uuid(self): |
|---|
| 0 | + | return self.name |
|---|
| 0 | + | |
|---|
| 0 | + | id(Test(name='toto')) == Test(name='toto') |
|---|
| 0 | + | t1 = Test(name='toto') |
|---|
| 0 | + | t2 = Test(name='toto') |
|---|
| 0 | + | |
|---|
| 0 | + | print id(t1) == id(t2) |
|---|
| 0 | + | t1.name = 'tata' |
|---|
| 0 | + | print t2.name |
|---|
| ... | |
|---|