簡體   English   中英

從不同的 class 修改 class 的另一種方法的變量

[英]Modifying variable of another method of a class from different class

我是 OOP 編程的新手,如果有人可以幫助我編寫這段代碼,那就太好了。 以下代碼是python中鏈表的起始代碼。

class Element(object):
    def __init__(self, value):
        self.value = value
        self.next = None

class LinkedList(object):
    def __init__(self, head=None):
        self.head = head
    def append(self, new_element):
        current = self.head
        if self.head:
            while current.next:
                current = current.next
            current.next = new_element
        else:
            self.head = new_element

有人可以幫助我了解當前變量在做什么嗎? 另外,如果有任何參考資料,我可以在 python 3 中獲得相同的內容。如果 next 屬於不同的 class 的不同方法,我無法理解如何更改。python3 中的類似理解會有所幫助

當前變量是我們用來遍歷完整鏈表並到達末尾的臨時變量。 我們從頭開始當前變量,然后如果有下一個,我們將當前變量分配給下一個。 例如:

element 1: [val : 1, next: element 2]
element 2: [val : 2, next: element 3]
element 3: [val : 3, next: None]

頭 = 元素 1
現在我們從current = element 1開始,如果current.next != None ,我們分配current = current.next (element 2)
同樣,現在current = element 2我們再次分配current = current.next (element 3)
現在current = element 3current.next = None ,我們將停止並分配current.next = new_element

關於我們如何更改next ,即使它屬於不同的 class 的不同方法: next不是屬於__init__ function 的局部變量。它是 class 的屬性(由關鍵字self指定)。 您可以 在此處詳細了解 class 的屬性以及 self 的含義

暫無
暫無

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

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