Skip to content

Instantly share code, notes, and snippets.

@apua
Last active September 12, 2015 18:51
Show Gist options
  • Save apua/d0369967c699833929c8 to your computer and use it in GitHub Desktop.
Save apua/d0369967c699833929c8 to your computer and use it in GitHub Desktop.
# Singleton.py
class SingletonClass:
# __init__ will be triggered if the obj returned from __new__ is instance of __class__
# thus __init__ should also check
_ = None
def __new__(cls, *a, **kw):
if cls._:
return cls._
else:
print("new")
return super().__new__(cls)
def __init__(self, *a, **kw):
if __class__._:
return
print("init")
__class__._ = self
for i in range(5):
print(SingletonClass())
class SingletonMetaclass(type):
_ = None
def __call__(cls, *a, **kw):
if __class__._:
return __class__._
else:
obj = super().__call__(*a, **kw)
__class__._ = obj
return obj
class C(metaclass=SingletonMetaclass):
def __new__(cls, *a, **kw):
print("new")
return super().__new__(cls)
def __init__(self, *a, **kw):
print("init")
for i in range(5):
print(C())
"""
new
init
<__main__.SingletonClass object at 0xffeda910>
<__main__.SingletonClass object at 0xffeda910>
<__main__.SingletonClass object at 0xffeda910>
<__main__.SingletonClass object at 0xffeda910>
<__main__.SingletonClass object at 0xffeda910>
new
init
<__main__.C object at 0xffedaa50>
<__main__.C object at 0xffedaa50>
<__main__.C object at 0xffedaa50>
<__main__.C object at 0xffedaa50>
<__main__.C object at 0xffedaa50>
"""
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment