Python 类型提示 - 指定 dict 子类的键、值类型 [英] Python type hints - specify key, value type for dict subclass
问题描述
说我有
class A(dict): pass
有没有办法指定 A 的键和值的类型?是否可以通过继承类型的方式来完成 - 所以 class B(A)
将继承例如键的类型值并且能够覆盖值的类型?
Is there any way to specify the type of the key and values of A ? Can it be done in a way that the types are inherited - so class B(A)
would inherit the type values for, say, key and would be able to override the type of value ?
理想情况下,这将通过 pep-0484 - 但请注意我使用的是 python 2,所以我需要一个带有类型注释的解决方案.但是,如果这是不可能的,则可以接受涉及元类或任何其他黑客的解决方案.
Ideally this would be done via the type hints introduced in pep-0484 - but note I am on python 2 so I would need a solution with type comments. If however this is not possible a solution involving metaclasses or any other hack would be acceptable.
推荐答案
与您的类的所有类型交互都通过方法进行,因此请对这些方法进行注释.A.__setitem__(self, key, value):
用于设置键值对,可以通过注释来指示预期的类型.
All type interactions with your class go through methods, so annotate those methods. A.__setitem__(self, key, value):
is called for setting a key-value pair and can be annotated to indicate the types expected.
此处可以使用任何有效的 PEP 484 注释,包括类型注释(如果您需要与 Python 2 兼容).
Any valid PEP 484 annotation would do here, including type comments if you need Python 2 compatibility.
除非 B 覆盖这些方法,否则这些注解将被继承给 B
.
Those annotations would be inherited to B
unless B overrides the methods.
这篇关于Python 类型提示 - 指定 dict 子类的键、值类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!