python - Python:指定与继承一起使用的类方法的返回类型
问题描述
我一直在尝试了解如何在 Python 中指定类方法的返回类型,以便即使对于子类也能正确解释它(例如在我的 Sphinx 文档中)。
假设我有:
class Parent:
@classmethod
def a_class_method(cls) -> 'Parent':
return cls()
class Child(Parent):
pass
a_class_method
如果我希望它Parent
用于父母和孩子,我应该指定什么作为返回类型Child
?我也试过__qualname__
了,但这似乎也不起作用。我应该不注释返回类型吗?
提前致谢!
解决方案
现在有支持的语法cls
,通过使用类型变量进行注释。引用 PEP 484 中的一个例子:
T = TypeVar('T', bound='C')
class C:
@classmethod
def factory(cls: Type[T]) -> T:
# make a new instance of cls
class D(C): ...
d = D.factory() # type here should be D
推荐阅读
- axon - 如何根据 Axon 中的条件读取和过滤实体聚合,然后更改它们
- assembly - ARM 汇编对 CortexM 的帮助
- aws-api-gateway - 从 api 网关运行批处理作业的语法
- oracle - 从另一个函数调用数据库连接(cx_Oracle)函数给出“AttributeError:'NoneType'对象没有属性'cusror'”
- karate - 我的代码有问题吗,因为函数中的逻辑在 js 中可以正常工作?
- javascript - jest 相当于 `mocha -g`(grep 选项)是什么?
- nightwatch.js - 在 nightwatchjs 中发送请求标头
- python - 类变量被压扁
- oracle - 动态构造 Sql 并检查表是否存在数据
- orientdb - OrientDB 与边缘属性匹配