创建一个子类ABCMeta
:
class SingletonABCMeta(ABCMeta):
_instances = {}
def __call__(cls, *args, **kwargs):
if cls not in cls._instances:
cls._instances[cls] = super(SingletonABCMeta, cls).__call__(*args, **kwargs)
return cls._instances[cls]
class GenericLogger(object):
__metaclass__ = SingletonABCMeta
@abstractproperty
def SearchLink(self): pass
class Logger(GenericLogger):
@property
def SearchLink(self): return ''
元类就像普通类一样工作;您仍然可以创建子类并扩展它们的功能。ABCMeta
它本身并没有定义__call__
方法,因此添加一个方法是安全的。
演示:
>>> from abc import ABCMeta, abstractproperty
>>> class SingletonABCMeta(ABCMeta):
... _instances = {}
... def __call__(cls, *args, **kwargs):
... if cls not in cls._instances:
... cls._instances[cls] = super(SingletonABCMeta, cls).__call__(*args, **kwargs)
... return cls._instances[cls]
...
>>> class GenericLogger(object):
... __metaclass__ = SingletonABCMeta
... @abstractproperty
... def SearchLink(self): pass
...
>>> class Logger(GenericLogger):
... @property
... def SearchLink(self): return ''
...
>>> Logger()
<__main__.Logger object at 0x1012ace90>
>>> Logger()
<__main__.Logger object at 0x1012ace90>
>>> class IncompleteLogger(GenericLogger):
... pass
...
>>> IncompleteLogger()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 5, in __call__
TypeError: Can't instantiate abstract class IncompleteLogger with abstract methods SearchLink