Python 如何声明包含类的dict的类型
我试图用Python 如何声明包含类的dict的类型,python,python-3.x,type-hinting,mypy,Python,Python 3.x,Type Hinting,Mypy,我试图用键入模块声明以下函数参数的类型: import typing class A(object): pass class B(A): pass class C(B): pass def my_func(p: typing.Dict[A, str]) -> None: pass my_func({C: 'foo'}) pmy_func的参数必须是dict,childclass的A作为键,str作为值。实际表示法失败,请检查mypy 示例.py
键入模块声明以下函数参数的类型:
import typing
class A(object):
pass
class B(A):
pass
class C(B):
pass
def my_func(p: typing.Dict[A, str]) -> None:
pass
my_func({C: 'foo'})
p
my_func
的参数必须是dict
,childclass的A
作为键,str
作为值。实际表示法失败,请检查mypy
示例.py:17:错误:列表项0具有不兼容的类型“Tuple[C,str]”
如何通过键入来声明p
的类型?代码使用类C
本身作为键,而不是C
的实例
my_func({C: 'foo'})
传递C类的实例应该可以
my_func({C(): 'foo'})
^^^--- instance, not a class itself
如果您确实需要通过课程本身(我对此表示怀疑),您需要使用:
谢谢。注意:我真的需要通过这门课。
typing.Dict[typing.Type[A], str]
^^^^^^^^^^^^^^