Python class methods and inheritance

I would expect the following code to print 012345, but it will print 012012. Why? I would expect incr calls to access the same variables as they inherit from the same class, but they are clearly different from the variables.

class a(object): var = 0 @classmethod def incr(cls): print cls.var cls.var+=1 class b(a): def func(self): super(b,self).incr() class c(a): def func(self): super(c,self).incr() t = a() t1 = b() t2 = c() t1.func() t1.func() t1.func() t2.func() t2.func() t2.func() 
+5
source share
2 answers

They inherit from the same class, but cls passed to classmethod via super is the current class from which the method was called. super refers to the version of the base class of the method, but the cls for the call is the class in which the super call was made.

This is one of the subtle differences between:

 def func(self): super(c, self).incr() # same as a.__dict__['incr'].__get__(self, type(self))() 

and

 def func(self): a.incr() 

You can confirm this by typing the current cls in your incr method in both cases:

 def incr(cls): print cls ... 

You must not allow all super execute a method call associated with the parent class. This is a lot more.

Keep in mind that when the first extended assignment += is executed, the initial value of var read from the base class (since at the moment it does not exist in dict subclasses). However, the updated value is written to a subclass. Calling super from the second subclass repeats the same behavior of reading the original var value from a .

+5
source

Both classes b and class c inherit from class a separately, and var set to 0 each time.

One way to have class c to get the same var value in class a as class b , class c can inherit from class b like this:

 class a(object): var = 0 @classmethod def incr(cls): print cls.var cls.var+=1 class b(a): def func(self): super(b,self).incr() class c(b): def func(self): super(c,self).incr() t = a() t1 = b() t2 = c() t1.func() t1.func() t1.func() t2.func() t2.func() t2.func()` 
0
source

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


All Articles