簡體   English   中英

為什么在 class 方法中創建 class 的實例會更改“self”參數?

[英]Why creating an instance of a class within a class method changes the 'self' argument?

我正在 Python 中編寫一個鏈接列表,我遇到了一個對於調試來說非常麻煩和可怕的問題,我覺得我錯過了一些關於 Python 的問題。 我應該創建一個具有一些基本功能的單鏈表。 其中一個是 take() function,它旨在創建一個包含原始列表的第 n 個元素的新列表。 但是,創建 LinkedList class 的新實例似乎更改了 .self 參數並且修改了變量節點,因為 attribute.next 變成了 None。 結果,當創建一個列表然后嘗試從其中的 n 個元素中創建一個新列表時,程序會無限期地運行,但是無論我查看哪一部分,我都找不到循環或它背后的原因。

class LinkedList:
    def __init__(self, head=None):
        self.head = head


    def is_empty(self):
        if self.head == None:
            return True
        else:
            return False

    def add_last(self, node):
        if self.is_empty():
            self.head = node
            return
        nextEl = self.head
        while True:
            if nextEl.next is None:
                nextEl.next = node
                return
            nextEl = nextEl.next


    def take(self, n):
        node = self.head
        newHead = self.head
        newHead.next = None
        newList = LinkedList(newHead)
        count = 0
        while count < n:
            newList.add_last(node.next)
            node = node.next
            count += 1
        return newList

class Node:
    def __init__(self, data, next=None):
        self.data = data
        self.next = next

謝謝你的幫助。

take() function 行

newHead.next = None

修改鏈表的一個節點,打破這個鏈表。 您可以按如下方式解決此問題:

def take(self, n):
    node = self.head
    newHead = Node(self.head.data)
    newList = LinkedList(newHead)
    count = 0
    while count < n:
        newList.add_last(node.next)
        node = node.next
        count += 1
    return newList

但是,這仍然無法正常工作,因為add_last() function 也存在問題。 我認為這個 function 應該添加一個節點作為鏈表的最后一個元素,但是由於您不修改節點的next屬性,因此實際上 append 是從該節點開始的整個鏈表。 這可以通過以下方式修復:

def add_last(self, node):
    if self.is_empty():
        self.head = node
        return
    nextEl = self.head
    while True:
        if nextEl.next is None:
            nextEl.next = Node(node.data)     
            return
        nextEl = nextEl.next

還有更多的問題。 例如, take(sefl, n)實際上會創建一個包含n+1元素的列表,如果它應用於沒有那么多元素的鏈表,則會拋出異常。

暫無
暫無

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

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