簡體   English   中英

更改類變量不會影響對象的值

[英]Changing class variable doesn't affect object's value

我正在嘗試教一個需要實例變量並使用self 因此,我提出了以下示例。 但是,它並沒有按照我的想法去做,哈哈。 我已經開始呼吁大家回答我的問題:盡管我正在更改類變量,但是使用x.one的最后一個print語句x.one也不會輸出-1

class example():
  one = 1
  two = 2

# Creating 2 'example' objects, x and y
x = example()
y = example()
print("x is: ", x.one, "y is: ", y.one) # output: x is 1, y is 1

# From the print statement, we'll see that changing one class object does not affect another class object
x.one = 0
print("x is: ", x.one, "y is: ", y.one) # output: x is 0, y is 1

# But what if we changed the class itself?
example.one = -1
print("x is: ", x.one, "y is: ", y.one) # output: x is 0, y is -1

我的猜測是,這與我在上面的塊中更改x.one的值有關,這使x.one可能在內存中具有新位置,而不是引用example.one在內存中的位置。

如果您能給我更詳細的理由,我將不勝感激,並且能夠將所學知識傳遞給我的學生。

開始時,沒有定義實例屬性,只有類屬性onetwo 因此,當您向實例xy詢問其屬性one ,它們首先檢查它們是否具有實例屬性,看是否沒有實例屬性,從而報告類屬性。

     Instance    Class
x                 *1*
y                 *1*

當您分配給x.one ,這實例x創建了一個名為one的實例屬性。 因此,當您再次詢問它們時, x報告其自己的實例值one y仍報告class屬性。

     Instance    Class
x      *0*         1
y                 *1*

然后,當您更改類屬性one ,這不會更改x因為它的實例屬性one仍優先於類屬性。 您會看到y的差異,因為它仍然沒有任何實例屬性,因此會繼續報告class屬性。

     Instance    Class
x      *0*        -1
y                *-1*

暫無
暫無

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

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