Skip to content

Instantly share code, notes, and snippets.

@aditya-gupta-sde
Created January 27, 2021 06:27
Show Gist options
  • Save aditya-gupta-sde/c26d7836c0bd46bb3fd7b9c03ee2811c to your computer and use it in GitHub Desktop.
Save aditya-gupta-sde/c26d7836c0bd46bb3fd7b9c03ee2811c to your computer and use it in GitHub Desktop.
An example Code for Singleton Class
class Singleton:
objects_created = 0
def __new__(cls,*args,**kwargs):
if cls.objects_created >= 1:
raise ValueError("This is a Singleton Class, can't create more objects!")
cls.objects_created +=1
return super().__new__(cls)
def __del__(self):
Singleton.objects_created -=1
def __init__(self):
print("Object Created, present count of object(s):" + str(Singleton.objects_created))
object1 = Singleton() #Object Created, number of created objects=1
object2 = Singleton()
'''
---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
<ipython-input-59-d021da9b783b> in <module>()
----> 1 object2 = Singleton()
<ipython-input-57-1799f9006989> in __new__(cls, *args, **kwargs)
3 def __new__(cls,*args,**kwargs):
4 if cls.objects_created >= 1:
----> 5 raise ValueError("This is a Singleton Class, can't create more objects!")
6 cls.objects_created +=1
7 print ("Object Created, number of created objects=" + str(cls.objects_created))
ValueError: This is a Singleton Class, can't create more objects!
'''
del object1
Singleton.objects_created #0
object2 = Singleton() #Object Created, number of created objects=1
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment