我有一堂课,看起来像这样,
class A:
def __init__(self, model):
self.model = model
def func(self, x: ???):
pass
我想使用我在
__init__
中传递给
func
的模型(正在使用 pydantic BaseModel)
def func(self, x: self.model):
pass
无效
您可以使课程变得通用,如下所示:
from typing import Generic, TypeVar
T = TypeVar("T")
class A(Generic[T]):
def __init__(self, model: T) -> None:
self.model = model
def func(self, x: T):
return
a = A(1)
reveal_type(a) # Revealed type is "A[int]"
reveal_type(a.func) # Revealed type is "def (x: int) -> Any"