擅长:python、mysql、java
<p>这是由于<a href="https://docs.python.org/3/tutorial/classes.html#private-variables" rel="noreferrer">name mangling</a>。Python将在内部将<code>__virt_method</code>重命名为基类中的<code>_A__virt_method</code>,并在派生类中将{<cd3>}重命名为:</p>
<blockquote>
<p>Any identifier of the form <code>__spam</code> (at least two leading underscores, at most one trailing underscore) is textually replaced with <code>_classname__spam</code>, where classname is the current class name with leading underscore(s) stripped.</p>
</blockquote>
<hr/>
<p>将该方法重命名为<code>_virt_method</code>(只有一个下划线),它将起作用:</p>
<pre><code>class A:
def __init__(self):
# base constructor implementation
pass
def _virt_method(self):
raise NotImplementedError()
def public_method(self):
self._virt_method()
class B(A):
def __init(self):
A.__init__(self)
# derived constructor implementation
pass
def _virt_method(self):
# some useful code here
pass
</code></pre>