Python子类计数器

Pie*_*uis 5 python counter subclass init

我有这个python代码。结果是TopTest: attr1=0, attr2=1X 很好,但结果是SubTest: attr1=2, attr2=3Y,我不太明白。

基本上,我有一个类属性,它是一个计数器,它在__init__ method. 当我启动 Y 时,计数器设置为 2,然后才分配属性。我不明白为什么它从 2 开始。子类不应该复制超类并且计数器从 0 重新开始吗?

class AttrDisplay: 
  def gatherAttrs(self):        
    attrs = []        
    for key in sorted(self.__dict__):            
        attrs.append('%s=%s' % (key, getattr(self, key)))        
    return ', '.join(attrs)
  def __repr__(self):        
    return '[%s: %s]' % (self.__class__.__name__, self.gatherAttrs())

class TopTest(AttrDisplay): 
    count = 0        
    def __init__(self):            
        self.attr1 = TopTest.count            
        self.attr2 = TopTest.count+1            
        TopTest.count += 2

class SubTest(TopTest):
    pass

X, Y = TopTest(), SubTest()         
print(X)                            
print(Y)                         
Run Code Online (Sandbox Code Playgroud)

Chr*_*ean 0

SubTest当创建的新实例TopTest.__init__()被调用时(因为SubTest继承了TopTest.__init__()),它会增加TopTest.count2。

由于SubTest从未定义类级别count变量,因此SubTest.count执行时,Python 会回退并使用TopTest.count.

count可以通过重新定义local to来修复此行为SubTest

class SubTest(TopTest):
    count = 0
Run Code Online (Sandbox Code Playgroud)