A code example of the SingletonMeta metaclass that implements the Singleton pattern in the class and the MySingleton class that applies it.
ex_meta_singleton.pyt
class SingletonMeta(type):
def __init__(cls, name, bases, disc, **kwargs):
cls.__instance = name
def __call__(cls, *args, **kwargs):
if cls.__instance is None:
cls.__instance = super().__call__(*args, **kwargs)
return cls.__instance
class MySingleton(metaclass = SingletonMeta):
pass
Self-study python Quoted from Chapter 11 Object-Oriented Syntax
Recommended Posts