擅长:python、mysql、java
<p><strong>基于这个和fwc:s的答案,我创建了一个pip可安装包<a href="https://github.com/mkorpela/overrides" rel="nofollow noreferrer">https://github.com/mkorpela/overrides</a></strong></p>
<p>有时我会在这里看到这个问题。
这主要发生在(再次)在我们的代码库中看到相同的错误之后:有人在重命名“interface”中的方法时忘记了一些实现类的“interface”。。</p>
<p>好吧,Python不是Java,但Python有强大的功能——显式比隐式更好——而且在现实世界中确实有一些具体的例子可以帮助我。</p>
<p>这里是覆盖decorator的草图。这将检查作为参数给定的类是否与要修饰的方法具有相同的方法(或其他)名称。</p>
<p>如果你能想出更好的解决办法,请贴在这里!</p>
<pre><code>def overrides(interface_class):
def overrider(method):
assert(method.__name__ in dir(interface_class))
return method
return overrider
</code></pre>
<p>其工作原理如下:</p>
<pre><code>class MySuperInterface(object):
def my_method(self):
print 'hello world!'
class ConcreteImplementer(MySuperInterface):
@overrides(MySuperInterface)
def my_method(self):
print 'hello kitty!'
</code></pre>
<p>如果执行错误的版本,则在类加载期间将引发断言错误:</p>
<pre><code>class ConcreteFaultyImplementer(MySuperInterface):
@overrides(MySuperInterface)
def your_method(self):
print 'bye bye!'
>> AssertionError!!!!!!!
</code></pre>