考虑这段代码
from abc import ABCMeta, abstractmethod
class C():
@abstractmethod
def my_abstract_method(self):
print('foo')
class D(C):
pass
x = C()
y = D()
mypy不允许x
或y
让我
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.570
和python 3.6.3
但是,文档说我需要设置metaclass=ABCMeta
才能正常工作。我错过了什么?
答案 0 :(得分:1)
好的,只有metaclass=ABCMeta
只有mypy
才会收到错误,而metaclass=ABCMeta
只有mypy
和python
会收到错误。
请参阅:
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