擅长:python、mysql、java
<p>你很接近——当你查找一个对象的属性时,你不一定要查找一个属于对象本身的属性。相反,查找遵循Python的<a href="https://stackoverflow.com/a/1848647"><strong>method resolution order</strong></a>,它。。。并不完全简单。但是,在这种情况下,只执行三个步骤:</p>
<ol>
<li>检查<code>Y</code>是否具有名为<code>count</code>的属性。在</li>
<li>它没有,所以检查它的类<code>SubTest</code>是否有一个名为<code>count</code>的属性。在</li>
<li>它没有,所以检查它的父项<code>TopTest</code>是否有一个名为<code>count</code>的属性。是的,所以访问那个。在</li>
</ol>
<p>简单地说,当您访问<code>Y.count</code>,<strong>实际上是在访问<code>TopTest.count</code></strong>。在</p>
<hr/>
<p>还有一个事实是,您的代码子测试增量<code>TopTest</code>的计数中有一个bug,而不是它自己的错误。你的问题的标题是“subclass counter”,但是由于你在<code>__init__()</code>中计数,我假设你在寻找一个<strong>实例计数器</strong>(要计算子类,我非常确定<a href="https://stackoverflow.com/questions/18126552/python-run-code-when-a-class-is-subclassed">you'd need to use metaclasses</a>)。这是<code>self.__class__</code>的完美用例,它是一个包含对象类的属性!为了使用它:</p>
<pre><code>def __init__(self):
self.attr1 = self.__class__.count
self.attr2 = self.__class__.count + 1
self.__class__.count += 2
</code></pre>
<p>使用它,当您调用<code>SubTest()</code>时,<code>SubTest.count</code>将递增,而不是{<cd8>}。在</p>