Python 加入类型注解后,父类到子类的强制转换怎么处理?

2022-07-06 17:14:08 +08:00
 lanlanye

先贴代码:

class AbstractMapper(ABC):

    def __init__(self):
        self._loaded_map: Dict["ObjectId", "DomainObject"] = {}

    def _abstract_find(self, id_: "ObjectId") -> "DomainObject":
        stmt = self.find_statement()
        try:
            rs = cursor.execute(stmt, (id_,)).fetchone()
            res = self._load(rs)
            return res
        except Exception as e:
            ...
        finally:
            ...

    def _load(self, rs: tuple) -> "DomainObject":
        if rs[0] in self._loaded_map:
            return self._loaded_map[rs[0]]
        res = self._do_load(rs)
        self._loaded_map[res.id] = res
        return res

    @abstractmethod
    def _do_load(self, rs: tuple) -> "DomainObject":
        ...

    @abstractmethod
    def find_statement(self) -> str:
        ...


class ArtistMapper(AbstractMapper):

    def find_statement(self) -> str:
        return "select id, name from artists where id = $1 limit 1"

    def _do_load(self, rs: tuple) -> "DomainObject":
        id_ = rs[0]
        name = rs[1]
        return Artist(id_, name)

    def find(self, id_) -> "Artist":
        return self._abstract_find(id_)  # Expression of type "DomainObject" cannot be assigned to return type "Artist"   "DomainObject" is incompatible with "Artist"

上面的代码中,_abstract_find() 的返回值标注为 DomainObject 类型,而在 ArtistMapper 中 find 方法需要返回一个 Artist 实例,Artist 是 DomainObject 的子类。

我看到 Java 代码中这里是通过强制类型转换解决的,Python 中这样的代码虽然可以正确运行,但无法通过静态类型检查,想知道有什么办法可以通过检查?

1898 次点击
所在节点    Python
5 条回复
shyrock
2022-07-06 17:29:26 +08:00
Artist 跟 DomainObject 什么关系?
lanlanye
2022-07-06 17:51:22 +08:00
@shyrock Artist 继承自 DomainObject
heqing
2022-07-06 18:20:50 +08:00
使用 Generic
hsfzxjy
2022-07-06 18:33:10 +08:00
粗暴点就用 typing.cast ,规范点就给 AbstractMapper 加范型参数
t2jk4000
2022-07-08 09:04:59 +08:00

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/864482

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX