Last active
August 7, 2018 13:40
-
-
Save 6aditya8/dc3c5cfbe0eda0c7ceaf69ba97cdadd8 to your computer and use it in GitHub Desktop.
An example Code for Singleton Class
This file contains 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