Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

please help me understanding python object instantiation.

I am not a programmer and I am trying to learn python at the moment. But I am a little confused with the object instantiation. I am thinking Class like a template and object is make(or instantiated) based on the template. Doesn't that mean once object is created(eg. classinst1 = MyClass() ), change in template shouldn't affect what's in the object?

In addition, the below code shows that I could change the class variable "common" but only if I haven't assign 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), then change my class variable "common" no longer affect classinst.common value????

Can someone please clarify for me why the code below behave such way? Is it common to all OO language or just one of the quirky 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
like image 481
user2480156 Avatar asked Mar 23 '23 14:03

user2480156


1 Answers

You have the general idea of class declaration and instantiation right. But the reason why the output in your example doesn't seem to make sense is that there are actually two variables called common. The first is the class variable declared and instantiated at the top of your code, in the class declaration. This is the only common for most of your example.

When you execute this line:

classinst1.common = 99

you are creating an object variable, a member of classinst1. Since this has the same name as a class variable, it shadows or hides MyClass.common. All further references to classinst1.common now refer to that object variable, while all references to classinst2.common continue to fall back to MyClass.common since there is no object variable called common that is a member of classinst2.

So when you execute:

MyClass.common = 7000

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

like image 118
dodgethesteamroller Avatar answered Mar 31 '23 21:03

dodgethesteamroller