How we can create singleton class in Python?

PythonServer Side ProgrammingProgramming

Singleton pattern provides a strategy to limit the number of the instances of the class to one. Thus the same object is always shared by different parts of the code. Singleton can be considered as a more elegant solution to global variable because actual data is hidden behind Singleton class interface.

The following code is one of the many different ways in which a singleton class can be created

class Singleton(object):
    _instance = None
    def __new__(class_, *args, **kwargs):
        if not isinstance(class_._instance, class_):
            class_._instance = object.__new__(class_, *args, **kwargs)
        return class_._instance
class MyClass(Singleton, BaseClass):
    pass

It's a true class

raja
Published on 23-Jan-2018 19:06:10
Advertisements