のサブクラスを作成します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