问题描述
谁能解释一下为什么要从未参数化和参数化的Callable
中继承:
Can someone explain why inheriting from unparameterized and parameterized Callable
:
from typing import Callable
from typing import NoReturn
from typing import TypeVar
T = TypeVar('T', str, int)
C = Callable[[T], NoReturn]
class Foo(Callable):
def __call__(self, t: T):
pass
class Bar(C):
def __call__(self, t: T):
pass
当传递给 mypy 时会引发 Foo
和 Bar
的错误:
when passed to mypy raises errors for both Foo
and Bar
:
tmp.py:13: error: Invalid base class
tmp.py:19: error: Invalid base class
推荐答案
这部分是因为运行时的类不能真正从函数或可调用的开始继承,部分是因为您不需要显式继承 Callable
以指示一个类是可调用的.
This is in part because classes at runtime can't really inherit from a function or a callable to begin with, and in part because you don't need to explicitly inherit from Callable
to indicate that a class is callable.
例如,以下程序使用 mypy 0.630 按预期进行类型检查:
For example, the following program typechecks as expected using mypy 0.630:
from typing import Callable, Union, NoReturn, List
class Foo:
def __call__(self, t: Union[str, int]) -> NoReturn:
pass
class FooChild(Foo): pass
class Bad:
def __call__(self, t: List[str]) -> NoReturn:
pass
def expects_callable(x: Callable[[Union[str, int]], NoReturn]) -> None:
pass
expects_callable(Foo()) # No error
expects_callable(FooChild()) # No error
expects_callable(Bad()) # Error here: Bad.__call__ has an incompatible signature
基本上,如果一个类有一个 __call__
方法,则隐含地假定该类也是一个可调用的.
Basically, if a class has a __call__
method, it's implicitly assumed that class is also a callable.
这篇关于Callable 是无效的基类?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!