我正在学习mtix6.00.1x计算机科学课程简介,在创建类方法时遇到了困难。特别是,我的'Queue'类中的'remove'函数没有像我预期的那样返回值。
以下是请求的上下文:
For this exercise, you will be coding your very first class, a Queue class. In your Queue class, you will need three methods:
init: initialize your Queue (think: how will you store the queue's elements? You'll need to initialize an appropriate object attribute in this method)
insert: inserts one element in your Queue
remove: removes (or 'pops') one element from your Queue and returns it. If the queue is empty, raises a ValueError.
我用“remove”方法编写了以下代码,但尽管该方法的行为正确地改变了数组,但它没有返回“popped”值:
class Queue(object):
def __init__(self):
self.vals = []
def insert(self, value):
self.vals.append(value)
def remove(self):
try:
self.vals.pop(0)
except:
raise ValueError()
任何帮助将不胜感激!
好吧,在Python中返回相当容易,所以只需执行以下操作:
幸运的是,
pop()
已经同时删除并返回所选元素。在您需要使用
return
来返回值。将移除方法更新为:必须显式返回该值:
还请注意:
list.pop()
方法的参数是可选的IndexError
,因此您应该只捕获特定的异常而不是每个异常vals
成员属于私有成员,因此rename it to start with an underscoreappend()
和{相关问题 更多 >
编程相关推荐