我正在尝试通过装饰器创建一个子类,并且还包括类型提示。 我设法获得了父方法或新子方法的类型提示,但没有获得它们的交集。我发现了类似的线程,但也许现在可以用 python 3.10+ 解决这个问题。
这里是一个示例代码:
from pydantic import BaseModel
import typing as t
T = t.TypeVar('T')
def wrapper(metaclass: t.Type[T]) -> t.Type[T]:
class sqlModel(metaclass):
def get_template_obj(self) -> str:
return 'example'
return sqlModel
@wrapper
class myTestModel(BaseModel):
kingappid: int = 17
exampleattr: str = 'example'
myTestModel().kingappid # has typehint
myTestModel().exampleattr # has typehint
myTestModel().get_template_obj() # doesn't have typehint
def wrapper2(metaclass):
class sqlModel(metaclass):
def get_template_obj(self) -> str:
return 'example'
return sqlModel
@wrapper2
class myTestModel2(BaseModel):
kingappid: int = 17
exampleattr: str = 'example'
myTestModel2().kingappid # doesn't have typehint
myTestModel2().exampleattr # doesn't have typehint
myTestModel2().get_template_obj() # has typehint
我已经尝试了几个线程提出的也使用协议的建议,但无法使其工作。