很好,请考虑下面的代码。
from abc import ABC, abstractmethod
class Interface(ABC):
@abstractmethod
def method(self) -> None:
pass
class A(Interface):
def method(self) -> None:
pass
class B(Interface):
def method(self) -> None:
pass
mapping = {'A': A, 'B': B}
# does NOT pass mypy checks
def create_map(param: str) -> Interface:
if param in mapping:
return mapping[param]()
else:
raise NotImplementedError()
# passes mypy checks
def create_if(param: str) -> Interface:
if param == 'A':
return A()
elif param == 'B':
return B()
else:
raise NotImplementedError()由于某些原因,create_if通过了所有的mypy类型检查,但create_map不能。这两个函数的reveal_type都是'def (param: builtins.str) -> test.Interface'。
我得到的错误与我试图直接实例化一个抽象类是一样的,这是奇怪的considering this reference for mypy。
error: Cannot instantiate abstract class 'Interface' with abstract attribute 'method'此外,如果我现在创建mapping = {'A': A} (即删除'B': B),create_map也会通过。
谁能解释一下这件事?
https://stackoverflow.com/questions/54241721
复制相似问题