Static variable in Python class | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
0

Static variable in Python class

Please help me with understanding this code: https://www.sololearn.com/compiler-playground/cGt22tFXkyZ1 Why do we get False at lines 12 and 18? Early I studied Java and there are no such strange things there: https://www.sololearn.com/compiler-playground/cKVq6c4x6H8m/#java

19th Oct 2022, 9:22 PM
Irakly Gagua
Irakly Gagua - avatar
3 Answers
0
In Python, the "is" operator is used to check if variable A points to the exact same object as variable B. In your case, if you compare the values of "d.K" and "NewClass.K", you'll see that whenever False is printed, "d.K" and "NewClass.K" do not reference the same object (the same number).
19th Oct 2022, 10:27 PM
Lee
0
Lee, thank you for the response. Why do d.K and NewClass.K reference the same object at the begining? Why do they stop doing it after "d.K = ..." but not after "NewClass.K = ..."?
19th Oct 2022, 10:53 PM
Irakly Gagua
Irakly Gagua - avatar
0
"K" is a static variable of the class "NewClass". Static variables can be accessed and modified without the need for an instance of the class. When you instantiate "NewClass", any static attributes are also "saved" to the new object. At the beginning, "NewClass.K" has a value of 1. Since "K" is a static variable, then "d.K" will also have the same value (1) - that's how static referencing works. However, now that you have an instance of "NewClass" (variable "d"), you can edit the attributes of it without conflicting with the actual class ("NewClass"). I hope this answers your first question. For the latter, when you assign a new value to "d.K" (line 11), you are changing the value of "K" of "d". Since "d" is an instance of the class "NewClass", the value of "NewClass.K" is not modified (as explained before). Nevertheless, when you set "NewClass.K" to the value of "d.K" (line 14), both will reference the same object and therefore True will be printed.
20th Oct 2022, 7:37 PM
Lee