你不能做你想要的只是ABCMeta
。 ABC强制执行任何类型检查,只有存在属性强制执行正确的名称。
举个例子:
>>> from abc import ABCMeta, abstractmethod, abstractproperty
>>> class Abstract(object):
... __metaclass__ = ABCMeta
... @abstractmethod
... def foo(self): pass
... @abstractproperty
... def bar(self): pass
...
>>> class Concrete(Abstract):
... foo = 'bar'
... bar = 'baz'
...
>>> Concrete()
<__main__.Concrete object at 0x104b4df90>
我能够构建即使两个foo
和bar
Concrete()
是简单的属性。
ABCMeta
元类仅跟踪有多少个对象,__isabstractmethod__
属性为true;当从元类创建类时(调用ABCMeta.__new__
)cls.__abstractmethods__
属性随后设置为frozenset
对象,并且所有名称仍然是抽象的。
type.__new__
然后测试那个frozenset
并抛出TypeError
如果您尝试创建一个实例。
您必须在此制作您的自己的__new__
方法;子类ABCMeta
,并在新的__new__
方法中添加类型检查。该方法应在基类上寻找__abstractmethods__
集合,在MRO中查找具有__isabstractmethod__
属性的相应对象,然后对当前类属性进行类型检查。
这意味着当定义类时,您会抛出异常,但不是实例。为了达到这个目的,你需要在你的ABCMeta
子类中添加一个__call__
方法,然后根据你自己的__new__
方法收集的信息来抛出异常:哪些类型是错误的;与目前ABCMeta
和type.__new__
所做的类似的两阶段过程。或者,更新该类上设置的__abstractmethods__
,以添加已实施但名称错误的任何名称,并将其保留为type.__new__
以引发异常。
下面的实现需要最后的粘性;名称添加回__abstractmethods__
如果(使用映射)实现的类型不匹配:
from types import FunctionType
class ABCMetaTypeCheck(ABCMeta):
_typemap = { # map abstract type to expected implementation type
abstractproperty: property,
abstractstatic: staticmethod,
# abstractmethods return function objects
FunctionType: FunctionType,
}
def __new__(mcls, name, bases, namespace):
cls = super(ABCMetaTypeCheck, mcls).__new__(mcls, name, bases, namespace)
wrong_type = set()
seen = set()
abstractmethods = cls.__abstractmethods__
for base in bases:
for name in getattr(base, "__abstractmethods__", set()):
if name in seen or name in abstractmethods:
continue # still abstract or later overridden
value = base.__dict__.get(name) # bypass descriptors
if getattr(value, "__isabstractmethod__", False):
seen.add(name)
expected = mcls._typemap[type(value)]
if not isinstance(namespace[name], expected):
wrong_type.add(name)
if wrong_type:
cls.__abstractmethods__ = abstractmethods | frozenset(wrong_type)
return cls
有了这个元类,你得到你期望的输出:
>>> class Abstract(object):
... __metaclass__ = ABCMetaTypeCheck
... @abstractmethod
... def foo(self): pass
... @abstractproperty
... def bar(self): pass
... @abstractstatic
... def baz(): pass
...
>>> class ConcreteWrong(Abstract):
... foo = 'bar'
... bar = 'baz'
... baz = 'spam'
...
>>> ConcreteWrong()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: Can't instantiate abstract class ConcreteWrong with abstract methods bar, baz, foo
>>>
>>> class ConcreteCorrect(Abstract):
... def foo(self): return 'bar'
... @property
... def bar(self): return 'baz'
... @staticmethod
... def baz(): return 'spam'
...
>>> ConcreteCorrect()
<__main__.ConcreteCorrect object at 0x104ce1d10>