

But suppose that you used a list: class ClassHavingAList(): Now in the case of immutable value such as int there is not that much difference. The newly created instance t2 will already have the attribute set. If you use _init_: > class Test2(object): i was looked up in the Test class for reading, but the new value was set into the t. There is no i attribute on the newly created t at all! Thus in t.i += 1 the. If that fails, the i attribute is looked up on type(i) instead (that is, the class attribute i).īut what this actually does is: > class Test(object): Now, when Python does the get attribute (as in print(instance.i) operation, it first looks for the attribute named i that is set on the instance). If no _init_ method is defined, the newly created instance usually starts with an empty instance dictionary, meaning that none of the properties are defined. All the variable declarations in the class body are stored as attributes of the class.

In python the instance attributes (such as self.i) are stored in the instance dictionary ( i._dict_). Why is that? Does that "=" create an " instance variable" named " i" without changing the original " Test4.i" by default? Yet the " append" method just handles the " class variable"?Īgain, thank you for your exhaustive explanation of the most boring basic concepts to a newbie of Python.

Shouldn't the int in the Test4 class also be changed by reference? If I change it in one instance, its value changes wherever I call it.īut that's not true for instances of Test4. And the instance_variable would be created distinctly for different instances.īut as I tried out, what you said is true for the Test3's instances, they all share the same memory. I created 2 new classes for understanding what you said: class Test3(object):Īs you said in the answer to my first questions, I understand the class_variable is a "class variable" general to the class, and should be passed or changed by reference to the same location in the memory. But, as I tried it further, I got yet another confusing problem. Now, I understand that they are different in a way that one is a "class variable", and the other is a "instance variable". Thank you very much Antti Haapala! Your answer gives me further understanding of my questions.
Python initiater code#
But is there any kind of “default” or “hidden” initialization mechanism of Python behind the scene when we don’t define the _init_ function for a class? And why I can’t write the first code in this way: class Test1(object): I know that the result or any instance created by these two class and the way of getting their instance variable are pretty much the same. What is the difference between these two pieces of code: class Test1(object): I’m confused about something described below. I found that some classes contain a _init_ function, and some don’t.
