“ Python:类对象不支持索引”错误

时间:2019-01-30 16:00:20

标签: python python-3.x

我正在尝试类,这是我第一次应用它们

这是班级:

class CreateArray:

   def __init__(self):
        array = []
        self.array = array
        print('How many elements?')
        ele = int(input())
        for j in range(ele):
            print('Enter element '+str(j+1))
            uin = int(input())
            array.append(uin)
        print('Array elements are: ')
        print(array)

    def __len__(self):
        return len(self.array)

这是我程序的一部分:

def comparedata(arr1, arr2):
    newlist = []
    arr1. __len__()
    if len(arr1) == len(arr2):
        for i in range(len(arr1)):
            if arr1[i] > arr2[i]: #indexing error occurs here
                newlist.append(arr1[i])

            elif arr1[i] < arr2[i]:
                newlist.append(arr2[i])

            print(newlist)


print('array 1 data: ')
arr1 = CreateArray()
print('array 2 data: ')
arr2 = CreateArray()
print('The two arrays are: ')
print(arr1.array)
print(arr2.array)
print('The greatest elements between the two arrays are: ')
comparedata(arr1,arr2)

我在if arr1[i]>arr2[i]遇到错误:

  

CreateArray对象不支持索引

由于未执行函数调用

2 个答案:

答案 0 :(得分:0)

这个问题似乎是这里堆栈溢出时其他几个问题的重复,但是希望下面的例子有所帮助。注意:我正在使用Python 3.7。最重要的是,您需要实现Sequence接口。

希望以下示例会有所帮助:

from collections.abc import Sequence

class MyArray(Sequence):
    def __init__(self, array):
        self.array = array

    def __getitem__(self, i):
        return self.array[i]

    def __len__(self):
        return len(self.array)

    @classmethod
    def from_input(cls):
        array = list()
        number_of_elements = int(input('How many elements? '))
        for i in range(number_of_elements):
            element = int(input("Type an integer"))
            array.append(element)
        return cls(array)

test1 = MyArray.from_input()

# How many elements? 4
# Type an integer: 1
# Type an integer: 2
# Type an integer: 3
# Type an integer: 4

test1[3]

# 4

test2 = MyArray.from_input()

# How many elements? 4
# Type an integer: 0
# Type an integer: 3
# Type an integer: 1
# Type an integer: 5

comparedata(test1, test2)
# [1]
# [1, 3]
# [1, 3, 3]
# [1, 3, 3, 5]

答案 1 :(得分:0)

您需要为您的类编写函数own_sum <- function(myobject, group, time){ mylist <- myobject[[group]] result <- 0 for(i in 1:length(mylist)){ result <- result + mylist[[i]][[time]] } return(result) } own_sum(biglist = workspace, group = 100, time = 3) # [1] 10 ,以支持__getitem__语法。例如,如果您查看list的文档,则会看到以下内容:

arr[i]

但是,如果您将比较写为:

|  __getitem__(...)
|      x.__getitem__(y) <==> x[y]