Skip to content

Instantly share code, notes, and snippets.

@meunomemauricio
Last active November 2, 2016 15:40
Show Gist options
  • Save meunomemauricio/07c5b9a4532fe0b71774a713dea124de to your computer and use it in GitHub Desktop.
Save meunomemauricio/07c5b9a4532fe0b71774a713dea124de to your computer and use it in GitHub Desktop.
Demo on how to define Singleton Classes on Python
#! /usr/bin/python
class Singleton(type):
_instances = {}
def __call__(cls, *args, **kwargs):
if cls not in cls._instances:
cls._instances[cls] = super(Singleton, cls).__call__(*args, **kwargs)
return cls._instances[cls]
class ExampleClass(object):
__metaclass__ = Singleton
def __init__(self):
self.name = 'World'
def set_name(self, name):
self.name = name
def say_hello(self):
print 'Hello, {0}!'.format(self.name)
if __name__ == '__main__':
print '{0:=^40}'.format(' Create Both Objects ')
obj1 = ExampleClass()
obj2 = ExampleClass()
print '{0:~^40}'.format(' Say Hello before setting any name. ')
obj1.say_hello()
obj2.say_hello()
print '{0:~^40}'.format(' Set Name on Obj 1 to "Earth" ')
obj1.set_name('Earth')
print '{0:~^40}'.format(' Say Hello only on Obj 2 ')
obj2.say_hello()
print '{0:~^40}'.format(' Set Name on Obj 2 to "Moon"')
obj2.set_name('Moon')
print '{0:~^40}'.format(' Say Hello only on Obj 1 ')
obj1.say_hello()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment