【问题标题】:How to import List from typing module to recognize the type List[int] in Class?如何从打字模块导入列表以识别类中的类型列表[int]?
【发布时间】:2020-01-19 05:05:33
【问题描述】:

在运行我的 python3 代码时,我收到以下错误:

'TypeError: 'type' 对象不可下标'

当我尝试将 __init__ class 参数设置为 List[int] 时,系统无法识别具有 List 参数的输入模块

我已经通过pip 安装了typing.py 模块并尝试使用import typing

即使系统无法识别类定义中的List[int] 类型。

下面是相同的代码,

from typing import List
class newcls:
    def __init__(self, a: int,arr: list[int]):
        self.a=a
        self.arr=arr
    def new1(self):
        print('a=',self.a)
        print(self.arr)
obj1=newcls(1,[1,2,3])
obj1.new1()

还有我在运行时收到的错误消息,

运行时错误为 def init(self, a: int,arr: list[int]):

TypeError:'type' 对象不可下标

【问题讨论】:

    标签: python-3.x list types importerror


    【解决方案1】:

    您的代码中有错字。 __init__ 函数的签名应为:

    def __init__(self, a: int,arr: List[int]):
    

    (注意大写List,不是内置类型list

    【讨论】:

    • 我已经试过 def __init__(self, a: int, b: int, arr: list[int]): TypeError: 'type' object is not subscriptable
    • 但是你还在用list?必须是 List,大写 L。
    • 首先我尝试了 import typing class newcls: def __init__(self, a: int,arr: List[int]): self.a = a self.arr=arr def prt(self): print (self.a) print(self.arr) obj1=newcls(1,[0,1,2]) obj1.prt()
    • def __init__(self, a: int,arr: List[int]): NameError: name 'List' is not defined
    • 然后我也尝试了小写。我知道问题出在哪里。但我不知道如何纠正。问题是由于命令导入键入。代码无法识别所有提示类型都存在的 typing.py 文件。我已经 pip 安装了,即使那样也没用。
    猜你喜欢
    • 2015-03-20
    • 1970-01-01
    • 2022-01-23
    • 2011-01-05
    • 2015-10-22
    • 1970-01-01
    • 2012-05-15
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多