i need to write a singleton so i looked up some examples. here's one of them from https://stackoverflow.com/questions/6760...on#6798042
i've just read about metaclasses but i don't understand how the above example uses a metaclass. shouldn't it be? -->
however i still want isinstance(inst, Singleton) to be True.
1 2 3 4 5 6 7 8 9 10 11 12 |
class _Singleton( type ): """ A metaclass that creates a Singleton base class when called. """ _instances = {} def __call__( cls , * args, * * kwargs): if cls not in cls ._instances: cls ._instances[ cls ] = super (_Singleton, cls ).__call__( * args, * * kwargs) return cls ._instances[ cls ] class Singleton(_Singleton( 'SingletonMeta' , ( object ,), {})): pass class Logger(Singleton): pass |
1 2 3 4 5 6 7 8 9 10 11 12 |
class _Singleton( type ): """ A metaclass that creates a Singleton base class when called. """ _instances = {} def __call__( cls , * args, * * kwargs): if cls not in cls ._instances: cls ._instances[ cls ] = super (_Singleton, cls ).__call__( * args, * * kwargs) return cls ._instances[ cls ] class Singleton(metaclass = _Singleton( 'SingletonMeta' , ( object ,), {})): pass # notice the metaclass class Logger(Singleton): pass |