类方法不返回valu

2024-04-25 12:35:03 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在学习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()

任何帮助将不胜感激!


Tags: the方法selfyouyourqueueinitdef
2条回答

好吧,在Python中返回相当容易,所以只需执行以下操作:

def remove(self):
    try:
        return self.vals.pop(0)
    except:
        raise ValueError()

幸运的是,pop()已经同时删除并返回所选元素。在

您需要使用return来返回值。将移除方法更新为:

def remove(self):
     try:
         return self.vals.pop(0)
     except:
         raise ValueError

必须显式返回该值:

return self.vals.pop()

还请注意:

  • list.pop()方法的参数是可选的
  • 它还将引发一个IndexError,因此您应该只捕获特定的异常而不是每个异常
  • 如果可能,您应该使用exception chaining
  • 您的vals成员属于私有成员,因此rename it to start with an underscore
  • 整个任务有些毫无意义,因为Python列表已经有了append()和{}方法,它们具有完全需要的行为。在

相关问题 更多 >