Class variable vs. Python instance variable for int value

I'm new to python and I'm not sure how this works. The code is as follows:

class test(): d=0 def __init__(self): self.d=self.d+1; D=test() print Dd D1=test() print D1.d D2=test() print D2.d 

Output

 1,1,1 # This should not be 

Now using this:

 class test(): d=[] def __init__(self): self.d.apend("1"); D=test() print Dd D1=test() print D1.d D2=test() print D2.d 

Result (it should be)

 ['1'] ['1', '1'] ['1', '1', '1'] 

So, I'm not sure why an integer value is not considered as a class variable during list processing.

+4
source share
4 answers

In the first example

 self.d = self.d + 1 

restores self.d , making it independent of test.d

In the second example

  self.d.append("1") 

modifies test.d

To verify this, type id(self.d) at the end of both constructors.

If you changed the second example to match the first:

  self.d = self.d + ["1"] 

you will see that the behavior would also change to match.

+3
source

If you want to change the class variable, do:

 class test(object): d=0 def __init__(self): type(self).d=self.d+1; D=test() print Dd D1=test() print D1.d D2=test() print D2.d 

You do not need type on the right side of the destination, because in this way you will never create an instance variable d . Please note that this requires new-style classes.

type is a function (actually called - it is also a class, but don't worry about it at the moment) that returns the class of its argument. So type(self) returns the class self . Classes are first class objects in Python.

Demo here: http://ideone.com/JdNpiV

Update: An alternative would be to use classmethod .

+3
source

To access a class variable, use class_name .variable_name, specifying:

 class test(object): d=0 def __init__(self): test.d = test.d + 1; 
0
source

NPE's answer tells you what is wrong with your code. However, I'm not sure if this really tells you how to solve the problem correctly.

Here, what I think you want if each test instance should have a different d value in the instance variable:

 class test(object): # new style class, since we inherit from "object" _d = 0 # this is a class variable, which I've named _d to avoid confusion def __init__(self): self.d = test._d # assign current value of class variable to an instance variable test._d += 1 # increment the class variable 

Now you can create multiple instances, and each will receive a unique value for d :

 >>> D0 = test() >>> D1 = test() >>> D2 = test() >>> print D0.d 0 >>> print D1.d 1 >>> print D2.d 2 
0
source

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


All Articles