将类型注释作为类中的参数传递

问题描述 投票:0回答:1

我有一堂课,看起来像这样,

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

无效

python annotations
1个回答
0
投票

您可以使课程变得通用,如下所示:

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"
© www.soinside.com 2019 - 2024. All rights reserved.