I have an abstract class and I would like to implement Singleton pattern for all classes that inherit from my abstract class. I know that my code won't work because there will be metaclass attribute conflict. Any ideas how to solve this?
from abc import ABCMeta, abstractmethod, abstractproperty
class Singleton(type):
_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 GenericLogger(object):
__metaclass__ = ABCMeta
@abstractproperty
def SearchLink(self): pass
class Logger(GenericLogger):
__metaclass__ = Singleton
@property
def SearchLink(self): return ''
a = Logger()
Create a subclass of
ABCMeta
:Metaclasses work just like regular classes; you can still create subclasses and extend their functionality.
ABCMeta
doesn't itself define a__call__
method, so it is safe to add one.Demo: