forked from gennad/Design-Patterns-in-Python
-
Notifications
You must be signed in to change notification settings - Fork 0
/
prototype.py
50 lines (38 loc) · 956 Bytes
/
prototype.py
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
from copy import deepcopy, copy
copyfunc = deepcopy
def Prototype(name, bases, dict):
class Cls:
pass
Cls.__name__ = name
Cls.__bases__ = bases
Cls.__dict__ = dict
inst = Cls()
inst.__call__ = copyier(inst)
return inst
class copyier:
def __init__(self, inst):
self._inst = inst
def __call__(self):
newinst = copyfunc(self._inst)
if copyfunc == deepcopy:
newinst.__call__._inst = newinst
else:
newinst.__call__ = copyier(newinst)
return newinst
class Point:
__metaclass__ = Prototype
x = 0
y = 0
def move(self, x, y):
self.x += x
self.y += y
a = Point()
print a.x, a.y # prints 0 0
a.move(100, 100)
print a.x, a.y # prints 100 100
Point.move(50, 50)
print Point.x, Point.y # prints 50 50
p = Point()
print p.x, p.y # prints 50 50
q = p()
print q.x, q.y # prints 50 50