Skip to main content
 首页 » 编程设计

python之Callable 是无效的基类

2024年12月31日9artech

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

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