【问题标题】:Variable isn't receiving the method's return value in Python变量未在 Python 中接收方法的返回值
【发布时间】:2017-07-20 22:48:39
【问题描述】:
def return_node(self, head, position):
    if position == 0:
        # return the node correctly
        return head
    else:
        self.return_node(head.next_node, position - 1)

def insert_at_position(self, head, data, position):
    if position == 0:
        self.insert_first(head, data)
    elif position == self.length:
        self.insert_last(head, data)
    else:
        previous_node = self.return_node(head, position - 1)
        # previous_node's value is None instead of the method's return value
        next_node = self.return_node(head, position)
        # same here
        new_node = Node(data, next_node)
        previous_node.next_node = new_node
        self.length += 1

我正在尝试在我的链表中实现一个在特定位置插入节点的方法。问题是:变量“previous_node”和“next_node”没有正确获取值。 他们得到的不是节点值,而是无。谢谢各位!

【问题讨论】:

  • return_node 的 else 没有 return 任何东西。
  • 你可能打算这样做return self.return_node(head.next_node, position - 1)

标签: python python-3.x methods return


【解决方案1】:
else:
  self.return_node(head.next_node, position - 1)

不会返回任何东西,因为没有return关键字。

return self.return_node(head.next_node, position - 1)

会做你正在寻找的。​​p>

【讨论】:

    【解决方案2】:

    将变量设置为None 的原因是,如果没有提供返回值,这是函数返回的默认值:

    def foo(): 
        pass 
    
    
    >>> type(foo())
    <class 'NoneType'>
    

    因为return_node() 内的else 子句不返回值,Python 返回None。如果要递归调用return_node,并返回后续调用返回的值,则需要使用return

    def return_node(self, head, position):
        if position == 0:
            # return the node correctly
            return head
        else:
            return self.return_node(head.next_node, position - 1) # use return
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-01-11
      • 2016-03-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-03-07
      相关资源
      最近更新 更多