考虑这段代码
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
才能起作用。我想念什么? 最佳答案
好的,没有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
关于python - @abstractmethod在不应该使用metaclass = ABCMeta的情况下可以正常工作,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/49297254/