首页 > 解决方案 > 如何正确使用类中的函数?

问题描述

我在实现类 ArrayQ 中的函数时遇到了困难。任务是创建一个类并在其中包含三个方法,入队、出队和 isEmpty。在“self.array.append(self.array)”中,我不确定它是否应该是数组、self.array、self 或括号中的其他内容。下面的 basictest() 函数用于控制我们的类是否可以正常工作,但目前还不能。

from array import array
    
class ArrayQ:
    def __init__(self,array):
        self.array = array

    def enqueue(self):
        self.array.append(self.array)

    def dequeue(self):
        self.array.pop(0)

    def isEmpty(self):
        if not self.array:
            print("queue is empty")

#print(ArrayQ)
lista = []

def basictest():
    q = ArrayQ(lista)
    q.enqueue(1)
    q.enqueue(2)
    x = q.dequeue()
    y = q.dequeue()
    if (x == 1 and y == 2):
        print("test OK")
    else:
        print("FAILED expexted x=1 and y=2 but got x =", x, " y =", y)
    
basictest()

我收到以下错误消息:

Traceback (most recent call last):
  File "d1.py", line 31, in <module>
    basictest()
  File "d1.py", line 22, in basictest
    q.enqueue(1)
TypeError: enqueue() takes 1 positional 
argument but 2 were given

那么有人可以指导我如何解决这个问题,以便我可以使这个代码工作吗?在这段代码中可能出现的几个错误中,为什么我不能使用“q.enqueue(1)”来使用类中编写的函数或方法来更改我的列表?

标签: pythonfunctionclassmethods

解决方案


你的问题就在这里。

def enqueue(self):
    self.array.append(self.array)

此方法需要一个参数:self. 它是该对象的引用,因此,除非您有一个类方法,否则您classmethod的类方法必须有一个self参数作为第一个参数。

现在,您的basictest()函数调用 aq.enqueue(1)但您的对象 q 是 aArrayQ并且它的enqueue函数只有一个参数:self。这是隐含的,你不能使用1as self。所以,enqueue以这种方式编辑:

def enqueue(self, value):
    self.array.append(value)

推荐阅读