Intellipaat Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Python by (47.6k points)

There seem to be many ways to define singletons in Python. Is there a consensus opinion on Stack Overflow?

1 Answer

0 votes
by (106k points)

Yes, there are many ways to define singleton I am mentioning one of them, what you can do is override the __new__ method like as follows:

class Singleton(object): 

_instance = None 

def __new__(cls, *args, **kwargs): 

if not cls._instance:

cls._instance = super(Singleton, cls).__new__( 

cls, *args, **kwargs) 

return cls._instance 

if __name__ == '__main__':

s1 = Singleton() 

s2 = Singleton() 

if (id(s1) == id(s2)):

print "Same"

else: 

print "Different"

31k questions

32.8k answers

501 comments

693 users

Browse Categories

...