【问题标题】:Type hinting in Python3.5 : Typed lists with aliasesPython3.5 中的类型提示:带别名的类型列表
【发布时间】:2021-09-08 03:37:01
【问题描述】:

对不起,我是新手,但我找不到任何方法来解决我的问题。

我正在 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-3.5 type-hinting


    【解决方案1】:

    旧版本的 Python 不支持这种语法,而从 Python 3.9 开始,它就可用了。

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

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

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

    【讨论】:

      猜你喜欢
      • 2022-08-04
      • 1970-01-01
      • 2014-10-06
      • 2021-01-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-10-18
      • 1970-01-01
      相关资源
      最近更新 更多