Skip to main content
 首页 » 编程设计

python之类方法没有返回值

2024年10月25日10kuangbin

我正在学习 MTIx 6.00.1x 计算机科学入门类(class),但在创建类(class)方法时遇到了问题。具体来说,我的“队列”类中的“删除”函数没有返回我期望的值。

这是请求的上下文:

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.

我用“删除”方法编写了以下代码,但尽管该方法的行为正确地改变了数组,但它没有返回“弹出”值:

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 中相当容易,所以只需这样做:

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

幸运的是,pop() 已经移除并同时返回了被选元素。