-
Notifications
You must be signed in to change notification settings - Fork 0
/
metatry.py
65 lines (46 loc) · 1.46 KB
/
metatry.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
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
class Meta(type):
instances = {}
def __init__(self, *args, **kwargs):
print 'Meta created', id(self)
def __new__(cls, name, bases, dct):
print 'meta new', cls, name, bases, dct.keys()
newdct = {}
for key, value in dct.items():
key = key.upper()
newdct[key] = value
dct.update(newdct)
return super(Meta, cls).__new__(cls, name, bases, dct)
def __call__(self, *args, **kwargs):
key = ((self.__module__ + '.')
if hasattr(self, '__module__') else '') + self.__name__
print ('meta __call__ called', self, args, kwargs, 'key=', key,
self.__name__)
if key in self.instances:
return self.instances.get(key)
obj = super(Meta, self).__call__(*args, **kwargs)
self.instances[key] = obj
return obj
class Singleton(object):
__metaclass__ = Meta
myAttr = 1
def __init__(self):
print 'object created'
def myFunc(self):
print 'myFunc called'
print 'class definition'
class AnotherSingleton(object):
__metaclass__ = Meta
def __init__(self):
print 'another object created'
def myFunc(self):
print 'another myFunc called'
print 'another class definition'
if __name__ == "__main__":
c = Singleton()
c.MYFUNC()
c.myFunc()
d = Singleton()
print id(c), id(d)
a = AnotherSingleton()
b = AnotherSingleton()
print id(a), id(b)