簡體   English   中英

變量未在Python中接收方法的返回值

[英]Variable isn't receiving the method's return value in Python

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”沒有正確獲取值。 他們沒有節點值,而是得到None。 感謝大伙們!

else:
  self.return_node(head.next_node, position - 1)

將不會返回任何內容,因為沒有return關鍵字。

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

會做您想要的。

將變量設置為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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM