考虑这段代码

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才能起作用。我想念什么?

最佳答案

好的,没有metaclass=ABCMeta的结果只有mypy会捕获到错误,而使用metaclass=ABCMetamypypython都会捕获到错误。

看到:

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/

10-12 22:21