小编osm*_*y88的帖子

如何从类属性动态设置类方法返回类型

我正在从事我的一个宠物项目,发现了这个小问题。我想在基类中使用类型,问题是类方法的返回类型是由子类设置的字段定义的。这是我的基类

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

    ...


Run Code Online (Sandbox Code Playgroud)

我想将函数的类型设置get为与模型字段中定义的对象类型相同。

关于如何完成类似的事情有什么建议吗?

python type-hinting python-3.x python-typing

1
推荐指数
1
解决办法
1378
查看次数

标签 统计

python ×1

python-3.x ×1

python-typing ×1

type-hinting ×1