python class methods and inheritance

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

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

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

    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()` 
    

提交回复
热议问题