擅长:python、mysql、java
<p>通常,如果希望通过修改扩展功能,但不完全替换基类方法,则可以执行此操作。<code>defaultdict</code>就是一个很好的例子:</p>
<pre><code>class DefaultDict(dict):
def __init__(self, default):
self.default = default
dict.__init__(self)
def __getitem__(self, key):
try:
return dict.__getitem__(self, key)
except KeyError:
result = self[key] = self.default()
return result
</code></pre>
<p>注意,正确的方法是<a href="https://stackoverflow.com/questions/222877/how-to-use-super-in-python">use ^{<cd2>} instead of directly calling the base class</a>。就像这样:</p>
<pre><code>class BlahBlah(someObject, someOtherObject):
def __init__(self, *args, **kwargs):
#do custom stuff
super(BlahBlah, self).__init__(*args, **kwargs) # now call the parent class(es)
</code></pre>