在 Python 中,如何指示我正在覆盖一个方法? [英] In Python, how do I indicate I'm overriding a method?

查看:15
本文介绍了在 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 这样的检查器的指示器,那是一种奖励).我可以在某处添加注释或文档字符串,但是在 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?

推荐答案

基于这个和 fwc:s answer 我创建了一个 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

它的工作原理如下:

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!!!!!!!

这篇关于在 Python 中,如何指示我正在覆盖一个方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆