python class methods and inheritance

后端 未结 3 2043
后悔当初
后悔当初 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:44

    There is a way to produce the sequence 012345. You have to make sure that the var of class a is increased in the incr method, even when it is called in the subclasses. To achieve this, increment by a.var += 1, not by cls.var += 1.

    As pointed out by the other answers, the var is also inherited to b and c. By using cls.var += 1 both subclasses increase their own var instead of a's var.

    class a:
        var = 0
        @classmethod
        def incr(cls):
            print(cls.var)
            a.var += 1
    
    class b(a):
        def f(self):
            super().incr()
    
    class c(a):
        def f(self):
            super().incr()
    
    cb = b()
    cc = c()
    cb.incr()
    cb.incr()
    cb.incr()
    cc.incr()
    cc.incr()
    cc.incr()
    
    cb.incr()
    cc.incr()
    

    Produces:

    0
    1
    2
    3
    4
    5
    6
    7
    

提交回复
热议问题