forked from colonelpanic/dotfiles
singleton with metaclass
This commit is contained in:
parent
a5ddc4f63c
commit
c1668ded37
24
dotfiles/lib/python/singleton.py
Normal file
24
dotfiles/lib/python/singleton.py
Normal 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
|
15
dotfiles/lib/python/singleton_test.py
Normal file
15
dotfiles/lib/python/singleton_test.py
Normal 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
|
Loading…
Reference in New Issue
Block a user