你正在寻找bound
:
T = TypeVar('T', bound=Callable)
来自文档:
类型变量可以使用
bound=<type>
指定上限。这意味着替换(明确或隐含地)类型变量的实际类型必须是边界类型的子类,参见PEP 484。
TypeVar(name, *args)
表示类型必须是args
之一,因此如果允许T = TypeVar('T', Callable)
,则所有T
的实例都可以被Callable
替换。
你应该能看到这里的不同之处(尽管我并没有真的尝试过,嘿):
from typing import Generic, TypeVar, Callable
T = TypeVar('T', Callable, bool)
class Foo(Generic[T]):
value: T
def __init__(self, value: T) -> None:
self.value = value
class Bar:
baz = 5
def __call__(self):
pass
f = Foo(Bar())
print(f.value.baz) # doesn’t typecheck because f.value is only a Callable
__init__
中调用T()
。 - alcornType[T]
类型的参数传递类。 - Ry-