【发布时间】:2021-10-19 10:54:34
【问题描述】:
我正在从事我的一个宠物项目,发现了这个小问题。我想在基类中使用类型,问题是类方法的返回类型是由子类设置的字段定义的。这是我的基类
class BaseRepository(metaclass=RequiredAttributes('model')):
model = None # The subclasses have to define the this field with a class type.
# All the class methods will return objects of the same
# type as this field.
def get(self, id) -> ??:
# return an object of the type defined in mode
...
class UserRepo(BaseRepository): # subclass
model = User # class type
...
我想将get 函数的类型设置为与模型字段中定义的对象类型相同。
有什么建议可以让我完成这样的事情吗?
【问题讨论】:
-
您可能想查看
typing.TypeVar。它可用于表示在给定范围内,多个变量共享同一类型。您可以使用T = TypeVar("T"),然后将-> T:作为返回类型。不幸的是,类型提示类属性使变量成为实例属性,所以这会使事情变得有点复杂。 -
@Carcigenicate:你忘了
typing.ClassVar吗?
标签: python python-3.x type-hinting python-typing