singleton with metaclass

This commit is contained in:
Ivan Malison 2015-08-20 02:11:55 -07:00
parent a5ddc4f63c
commit c1668ded37
2 changed files with 39 additions and 0 deletions

View File

@ -0,0 +1,24 @@
def singleton(klass):
original_init = klass.__dict__.get('__init__')
class klassMeta(type, klass):
def __init__(self, *args):
original_init(self)
super(klass, self).__init__(*args)
class Temp(object):
__metaclass__ = klassMeta
Temp.__name__ = klass.__name__
klassMeta.__name__ = "{}Meta".format(klass.__name__)
return Temp
@singleton
class TestSingleton(object):
def __init__(self):
self.a = 22
self.b = 44
def hey(self):
return self.a + self.b

View File

@ -0,0 +1,15 @@
from . import singleton
def test_singleton():
@singleton.singleton
class TestSingleton(object):
def __init__(self):
self.a = 22
self.b = 44
def hey(self):
return self.a + self.b
assert TestSingleton.a == 22
assert TestSingleton.hey() == 66