gpt4 book ai didi

python - Callable 是无效的基类?

转载 作者:太空宇宙 更新时间:2023-11-04 04:30:58 28 4
gpt4 key购买 nike

有人可以解释为什么要继承未参数化和参数化的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 时会引发 FooBar 的错误:

tmp.py:13: error: Invalid base class
tmp.py:19: error: Invalid base class

最佳答案

这部分是因为运行时的类不能真正从函数或可调用函数继承,部分是因为您不需要显式继承 Callable 来表明一个类是可调用的。

例如,以下程序使用 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__ 方法,它就隐含地假定该类也是一个可调用的。

关于python - Callable 是无效的基类?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52652595/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com