Please help me understand the python object instance.

I am not a programmer, and now I'm trying to learn python. But I'm a little confused about creating an object. I think the class is like a template, and the object is created (or created) based on the template. Does this mean that after creating the object (for example, classinst1 = MyClass ()), changing the template should not affect what is in the object?

In addition, the code below shows that I can change the variable of the "common" class, but only if I have not assigned a new value to the "common" variable in the object. If I assign a new value to β€œcommon” in my object (say classinst1.common = 99), change the class variable β€œcommon” to no longer affect the value of classinst.common <? >

Can someone explain to me why the code below behaves this way? Is this common to all OO languages, or just one of the bizarre aspects of python?

================

>>> class MyClass(object): ... common = 10 ... def __init__(self): ... self.myvar=3 ... def myfunction(self,arg1,arg2): ... return self.myvar ... >>> classinst1 = MyClass() >>> classinst1.myfunction(1,2) 3 >>> classinst2 = MyClass() >>> classinst2.common 10 >>> classinst1.common 10 >>> MyClass.common = 50 >>> classinst1.common 50 >>> classinst2.common 50 >>> classinst1.common = 99 >>> classinst2.common 50 >>> classinst1.common 99 >>> MyClass.common = 7000 >>> classinst1.common 99 >>> classinst2.common 7000 
+4
source share
1 answer

You have a basic understanding of class declaration and instance rights. But the reason the output in your example doesn't make sense is because there really are two variables called common . The first is a class variable, declared and created at the beginning of your code, in the class declaration. This is the only common for most of your examples.

When executing this line:

 classinst1.common = 99 

an object variable is created, a member of classinst1 . Since this is the same name as the class variable, it hides or hides MyClass.common . All further references to classinst1.common now refer to this object variable, and all references to classinst2.common continue to return to MyClass.common , since there is no object variable named common , which is a member of classinst2 .

So, when you do:

 MyClass.common = 7000 

this modifies MyClass.common , but classinst1.common remains equal to 99. In the final lines of your example, when you ask for an interpreter for the values ​​of classinst1.common and classinst2.common , the former refers to classinst1 member variable of the common object, while the latter refers to the class variable MyClass.common .

+7
source

Source: https://habr.com/ru/post/1485891/


All Articles