python - 如何正确使用类中的函数?
问题描述
我在实现类 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)”来使用类中编写的函数或方法来更改我的列表?
解决方案
你的问题就在这里。
def enqueue(self):
self.array.append(self.array)
此方法需要一个参数:self
. 它是该对象的引用,因此,除非您有一个类方法,否则您classmethod
的类方法必须有一个self
参数作为第一个参数。
现在,您的basictest()
函数调用 aq.enqueue(1)
但您的对象 q 是 aArrayQ
并且它的enqueue
函数只有一个参数:self
。这是隐含的,你不能使用1
as self
。所以,enqueue
以这种方式编辑:
def enqueue(self, value):
self.array.append(value)
推荐阅读
- vespa - Vespa 应用程序配置最佳实践
- git - Change base branch to remote master from forked master
- c++ - 避免 local() 调用 tbb enumerable_thread_specific 变量
- python - 使用pickle文件设置类属性?
- redisearch - 如何使用 Redisearch 从 FT.AGGREGATE 获取文档 ID?
- javascript - Javascript汉堡菜单触发但不可见?
- r - if (xn == xx) { 中的错误:需要 TRUE/FALSE 的缺失值
- r - Cumsum 函数结果与迭代循环不同
- sql - 将两个 sql 查询合并到一个表中
- scala - Spark sql如何使用层次结构类型表爆炸行