我正在尝试在python中创建一个数组,但是我无法打印该数组中的所有元素?

时间:2019-07-05 17:40:02

标签: python-3.x data-structures

试图使函数能够打印所有动态存储在其中的数组。但是我无法创建一个函数来打印数组中的所有元素

import ctypes

class myArray(object):
def __init__(self):
    self.length = 0
    self.capacity = 1
    self.Array = self.make_array(self.capacity)

def push(self, item):
    if self.length == self.capacity:
        self.resize(2*self.capacity)

    self.Array[self.length] = item
    self.length += 1
    print("Hello")

def getitem(self, index):
    if index >= self.length:
        return IndexError('Out Of Bounds')
    return self.Array[index]

def resize(self, new_cap):
    newArray = self.make_array(new_cap)

    for k in range(self.length):
        newArray[k] = self.Array[k]

    self.Array = newArray
    self.capacity = new_cap


def make_array(self, new_cap):
    return (new_cap * ctypes.py_object)()  

1 个答案:

答案 0 :(得分:1)

方法1:添加一种print_all()方法

def print_all(self):
    print(self.Array[:self.length])

方法2:创建类的字符串表示形式

def __str__(self):
    return str(self.Array[:self.length])

简单测试:

arr = myArray()
arr.push(5)
arr.push(2)
arr.push(3)
arr.push(5)
arr.push(4)
arr.push(6)
arr.print_all()
print(arr)

输出:

你好

你好

你好

你好

你好

你好

[5、2、3、5、4、6]

[5、2、3、5、4、6]

类的完整定义:

import ctypes

class myArray(object):
    def __init__(self):
        self.length = 0
        self.capacity = 1
        self.Array = self.make_array(self.capacity)

    def push(self, item):
        if self.length == self.capacity:
            self.resize(2*self.capacity)

        self.Array[self.length] = item
        self.length += 1
        print("Hello")

    def getitem(self, index):
        if index >= self.length:
            return IndexError('Out Of Bounds')
        return self.Array[index]

    def resize(self, new_cap):
        newArray = self.make_array(new_cap)

        for k in range(self.length):
            newArray[k] = self.Array[k]

        self.Array = newArray
        self.capacity = new_cap

    def make_array(self, new_cap):
        return (new_cap * ctypes.py_object)()  

    def print_all(self):
        print(self.Array[:self.length])

    def __str__(self):
        return str(self.Array[:self.length])