@abstractmethod工作正常,没有metaclass = ABCMeta,它不应该

时间:2018-03-15 10:39:00

标签: python abc

考虑这段代码

from abc import ABCMeta, abstractmethod

class C():
    @abstractmethod
    def my_abstract_method(self):
        print('foo')

class D(C):
    pass

x = C()
y = D()

mypy不允许xy让我

test.py:13: error: Cannot instantiate abstract class 'C' with abstract attribute 'my_abstract_method'
test.py:15: error: Cannot instantiate abstract class 'D' with abstract attribute 'my_abstract_method'

我正在使用mypy 0.570python 3.6.3

对此进行测试

但是,文档说我需要设置metaclass=ABCMeta才能正常工作。我错过了什么?

1 个答案:

答案 0 :(得分:1)

好的,只有metaclass=ABCMeta只有mypy才会收到错误,而metaclass=ABCMeta只有mypypython会收到错误。

请参阅:

from abc import abstractmethod

class C():
    @abstractmethod
    def my_abstract_method(self):
        print('foo')

class D(C):
    pass

x = C()
y = D()

$ mypy test.py 
test.py:13: error: Cannot instantiate abstract class 'C' with abstract attribute 'my_abstract_method'
test.py:15: error: Cannot instantiate abstract class 'D' with abstract attribute 'my_abstract_method'

但是

$ python3 test.py
$

然而,python也将捕获错误。

from abc import ABCMeta, abstractmethod

class C(metaclass=ABCMeta):
    @abstractmethod
    def my_abstract_method(self):
        print('foo')

class D(C):
    pass

x = C()

y = D()


$ python3 test.py 
Traceback (most recent call last):
  File "test.py", line 11, in <module>
    x = C()
TypeError: Can't instantiate abstract class C with abstract methods my_abstract_method