在Python中,我如何表明我重写了一个方法?
在Java中,例如, @Override
注释不仅提供了覆盖的编译时检查,而且还提供了出色的自我记录代码。
In Java, for example, the @Override
annotation not only provides compile-time checking of an override but makes for excellent self-documenting code.
我只是在寻找文件(虽然如果它是像pylint这样的检查器的指示器,那就是奖金)。我可以在某处添加注释或docstring,但在Python中指示覆盖的惯用方法是什么?
I'm just looking for documentation (although if it's an indicator to some checker like pylint, that's a bonus). I can add a comment or docstring somewhere, but what is the idiomatic way to indicate an override in Python?
更新(2015年5月23日):根据这个和fwc:s的答案我创建了一个pip可安装程序包 https://github.com/mkorpela/overrides
UPDATE (23.05.2015): Based on this and fwc:s answer I created a pip installable package https://github.com/mkorpela/overrides
我不时会在这里看到这个问题。
主要是在(再次)在我们的代码库中看到相同的错误之后发生:有人在接口中重命名方法时忘记了实现类的一些接口..
From time to time I end up here looking at this question. Mainly this happens after (again) seeing the same bug in our code base: Someone has forgotten some "interface" implementing class while renaming a method in the "interface"..
Python不是Java,而是Python有能力 - 而且显性比隐含更好 - 在现实世界中有真实的具体案例可以帮助我。
Well Python ain't Java but Python has power -- and explicit is better than implicit -- and there are real concrete cases in the real world where this thing would have helped me.
所以这里是覆盖装饰器的草图。这将检查作为参数给出的类与正在装饰的方法具有相同的方法(或其他)名称。
So here is a sketch of overrides decorator. This will check that the class given as a parameter has the same method (or something) name as the method being decorated.
如果您能想到更好的解决方案,请发布它在这里!
If you can think of a better solution please post it here!
def overrides(interface_class):
def overrider(method):
assert(method.__name__ in dir(interface_class))
return method
return overrider
It工作原理如下:
class MySuperInterface(object):
def my_method(self):
print 'hello world!'
class ConcreteImplementer(MySuperInterface):
@overrides(MySuperInterface)
def my_method(self):
print 'hello kitty!'
如果你做错了版本,它会在课堂加载期间引发一个断言错误:
and if you do a faulty version it will raise an assertion error during class loading:
class ConcreteFaultyImplementer(MySuperInterface):
@overrides(MySuperInterface)
def your_method(self):
print 'bye bye!'
>> AssertionError!!!!!!!