簡體   English   中英

有人可以幫我理解 class 變量嗎

[英]Can someone help me understand class variables

我試圖了解 class 變量以及如何更改它們,我不明白為什么在此示例代碼中,b 沒有更改為 9999。我試圖永久更改 b 以便任何時候從其他任何地方調用 What.b在代碼中,它將打印 9999。

class Whatever():
    b = 5
    def __init__(self):
        Whatever.b = 9999

class test():
    print(Whatever.b)

Whatever()
test()

這輸出:

5

test()調用無關緊要。 定義test class 期間執行打印。 那是在實例化Whatever東西之前,所以它是在 class 屬性設置為 9999 之前。

class Whatever():
    b = 5
    def __init__(self):
        Whatever.b = 9999

class test():
    print(Whatever.b)
# Now the print happens (while Whatever.b is still 5)

Whatever()
# Now Whatever.b is 9999
test()

如果在實例化了Whatever()之后的任何一點檢查Whatever.b的值,您會發現該值確實已更改為 9999。

問題是 test() 行不是使 5 打印出來的行。 我可以跑:

class Whatever():
    b = 5
    def __init__(self):
        Whatever.b = 9999

class test():
    print(Whatever.b)

Whatever()

並且它仍然會 output 5 ,因為print語句在 class test的定義期間運行。

基本上,您的 class test所做的就是打印Whatever.b而不初始化 class WhateverWhatever.b永遠不會設置為9999

要獲得9999輸出,您需要在 class 定義中首先初始化Whatever內容,如下所示:

class Whatever():
    b = 5
    def __init__(self):
        Whatever.b = 9999

class test():
    Whatever()
    print(Whatever.b)

Whatever()

在 test() class 上,您需要像這樣實例化whatever():

    myWhatever = Whatever()
    print(myWhatever.b)

然后只運行 Test()

https://www.digitalocean.com/community/tutorials/understanding-class-and-instance-variables-in-python-3

問題是test中的打印語句發生在 class 被定義時,而不是在它被實例化時。 因為它在定義時發生,所以它發生在調用Whatever()之前,因此b沒有被重置。

將可執行代碼放在 class 中但在任何方法之外是不常見的。 將代碼的行為與您在定義Test時得到的 output 進行對比,如下所示:

class test():
    def __init__(self):
        print(Whatever.b)

當我進行上述更改時,output 顯示 b 現在是 9999。這是因為 print 語句發生在您創建test實例時,而不是在您定義 class 時,並且因為您在創建實例后創建了Whatever的實例。

暫無
暫無

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

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