Skip to content

Instantly share code, notes, and snippets.

@uoxiu
Last active June 27, 2019 11:45
Show Gist options
  • Save uoxiu/81432f1762599c55b0d229424bb69d64 to your computer and use it in GitHub Desktop.
Save uoxiu/81432f1762599c55b0d229424bb69d64 to your computer and use it in GitHub Desktop.
Python Singleton
"""
Singleton implementation
"""
class Singleton(type):
_instances = {}
def __call__(self, *args, **kwargs):
if self not in self._instances:
self._instances[self] = super(Singleton, self).__call__(*args, **kwargs)
return self._instances[self]
def __copy__(cls, instance):
return instance
@classmethod
def create(cls, class_object, class_name=None):
return Singleton(class_name if class_name else class_object.__name__, (class_object,), {})
"""
Class for singletoning
"""
class RegisterClass(object):
def __init__(self):
self.l = []
def add(self, a):
self.l.append(a)
"""
One line creation of singleton
"""
A = Singleton.create(RegisterClass, 'A')
B = Singleton.create(RegisterClass, 'B')
"""
Operation with singleton
"""
print(A.__name__)
print(B.__name__)
a = A()
a.add(1)
b = B()
b.add(2)
print('a', a.l)
print('b', b.l)
a = A()
a.add(3)
b = B()
b.add(4)
print('a', a.l)
print('b', b.l)
@gruia-dev
Copy link

awesome!!!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment