簡體   English   中英

如何訪問和修改 python class 中的全局變量

[英]How to access and modify global variables in python class

我是 Python 課程的新手。 我試圖編寫一個鏈表程序,我需要一個全局變量來計算節點數,而不是 function。 因此,當我執行以下操作時:

class DoublyLinkedList:
    def __init__(self):
        self.head = None
        self.tail = None
        self.count = 0

Then outside the linked list class I was unable to access this self.count (in the part where I created the object of this class etc.) I thought that since it is a local variable to this class I was getting the error. 所以,我嘗試了這個:

count = 0
class DoublyLinkedList:
    def __init__(self):
        self.head = None
        self.tail = None
        global count
        self.count=0

我在想,如果我將全局變量設為這個 class 的數據字段,那么我不需要寫:

global count

在此 class 下的每個 function 中。 但是每當我訪問計數時,在 class 之外,它的值為零。 有人可以幫忙嗎。

編輯:顯示 function 不需要這個計數,所以我可以看到我的列表正在完美創建。 我只想使用 class 之外的計數訪問節點數,以便我可以在調用插入或刪除函數等之前檢查 position 的有效性等。如果有幫助,我將附加給我錯誤的片段:

pos = int(input("Enter the position : \n"))
if (pos>(count+1))or(pos<1):
    print("Invalid Position")

無需在 class 中創建全局變量,而是可以創建一個self.[variable name]但是要更改變量值,你可以self.[var name] = [new value]例如:

class myclass:
    def __init__(self):
        self.counter = 1

classvar = myclass();
print(classvar.counter)

我認為您誤解了關鍵字global的含義。 當您想要訪問/修改在普通腳本中定義的變量時使用global ,而不是在 function 中,例如

#test.py
c = 1

def test1():
    c = 3 #this will not modify the c which we declared earlier

test1()
print(c) #will print 1

def test2():
     global c #this tells the interpreter to look for the previously defined c
     c = 3
test2()
print(c) #will print 3

現在要訪問 object 的成員,您只需要使用objectname.variablename

在 class 中使用 global 是不常見的。 要訪問您的 class 屬性,您只需實例化一個新的 object。

class Car:
    def __init__(self):
    self.color = 'red'
    self.number_of_door = 5

# let's say I want to get the number of doors and plus one for Toyota

Toyota = Car()
print(Toyota.number_of_door + 1)


暫無
暫無

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

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