【问题标题】:'method' object is not subscriptable. Don't know what's wrong“方法”对象不可下标。不知道怎么了
【发布时间】:2016-02-08 00:54:44
【问题描述】:

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

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]

【问题讨论】:

    标签: python python-3.x


    【解决方案1】:

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

    【讨论】:

      【解决方案2】:

      试试这个:

      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])
      

      这会奏效。 在制作类的对象时,您忘了放括号。

      【讨论】:

        猜你喜欢
        • 2015-12-31
        • 1970-01-01
        • 2020-04-17
        • 2019-09-18
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-06-27
        • 1970-01-01
        相关资源
        最近更新 更多