Python “方法”对象不可下标。不知道怎么回事

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/35261055/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 16:12:29  来源:igfitidea点击:

'method' object is not subscriptable. Don't know what's wrong

pythonpython-3.x

提问by Ecoturtle

I'm writing some code to create an unsorted list but whenever I try to insert a list using the insert method I get the 'method' object is not subscriptable error. Not sure how to fix it. Thanks.

我正在编写一些代码来创建一个未排序的列表,但是每当我尝试使用 insert 方法插入一个列表时,我都会收到“方法”对象不可下标的错误。不知道如何修复它。谢谢。

class UnsortedList:
    def __init__(self):
        self.theList = list()
    def __getitem__(self, i):
       print(self.theList[i])
    def insert(self, lst):
        for x in lst:
            try:
                self.theList.append(float(x))
            except:
                print("oops")


myList = UnsortedList()
myList.insert[1, 2, 3]

回答by zondo

You need to use parentheses: myList.insert([1, 2, 3]). When you leave out the parentheses, python thinks you are trying to access myList.insertat position 1, 2, 3, because that's what brackets are used for when they are right next to a variable.

您需要使用括号:myList.insert([1, 2, 3]). 当您省略括号时,python 认为您正在尝试访问myList.insertposition 1, 2, 3,因为这就是括号在变量旁边时的用途。