python class methods and inheritance

后端 未结 3 2046
后悔当初
后悔当初 2021-01-18 18:28

I would expect the following code to print 012345 but it prints 012012. Why? I would expect the calls to incr to be accessing the same variables since they are inherited fro

3条回答
  •  不知归路
    2021-01-18 18:53

    They are inherited from the same class, but the cls passed to the classmethod via super is the current class where the method was called from. super accesses the base class version of the method, but the cls for the call is the class where the super call was made.

    This is one of the subtle differences between doing:

    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 printing the current cls in your incr method in both cases:

    def incr(cls):
        print cls
        ...
    

    You should never assume that all super does is make a method call bound to the parent class. It does a lot more.

    Keep in mind that when the first augmented assignment += is performed, the initial value of var is read from the base class (since at this point it does not exist in the dict of the subclasses). The updated value is however written to the subclass. Calling super from the second subclass repeats the same behavior of reading the initial var value from a.

提交回复
热议问题