微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

Python3.5 中的类型提示:带别名的类型列表

如何解决Python3.5 中的类型提示:带别名的类型列表

抱歉我是新手,但我找不到任何方法解决我的问题。

我正在 3.5.10 版本上开发 Python 应用程序。

    def doStuff(self) -> List[MyClass]:
        variable1 = MyClass()
        myList = list()
        myList.append(variable1)
        return myList

我希望能够使用 this Python documentation

中提到的别名

我试图为我的列表创建别名,但它不起作用:

MyAlias = list[MyClass]

我也尝试输入文档中的代码。它也不起作用:

Python 3.5.10 (default,Feb 20 2021,21:50:32)
[GCC 9.3.0] on linux
Type "help","copyright","credits" or "license" for more information.
>>> Vector = list[float]
Traceback (most recent call last):
  File "<stdin>",line 1,in <module>
TypeError: 'type' object is not subscriptable
>>>

我做错了什么吗?

解决方法

较旧版本的 Python 不支持此语法,而从 Python 3.9 开始可用。

>>> Vector = list[float]
>>>

PEP 585 引入了这种语法。在 3.5 之后的旧 Python 版本中,语法如下

>>> import typing
>>> Vector = typing.List[float]

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。