Created
January 27, 2021 06:27
-
-
Save aditya-gupta-sde/c26d7836c0bd46bb3fd7b9c03ee2811c to your computer and use it in GitHub Desktop.
An example Code for Singleton Class
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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