如何在 Python 类中检测重复的方法名称? [英] How can I detect duplicate method names in a Python class?

查看:44
本文介绍了如何在 Python 类中检测重复的方法名称?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在编写单元测试时,我有时会剪切和粘贴测试并且不记得更改方法名称.这会导致覆盖之前的测试,有效地隐藏它并阻止它运行.例如;

When writing unit tests, I sometimes cut and paste a test and don't remember to change the method name. This results in overwriting the previous test, effectively hiding it and preventing it from running. For example;

class WidgetTestCase(unittest.TestCase):

  def test_foo_should_do_some_behavior(self):
    self.assertEquals(42, self.widget.foo())

  def test_foo_should_do_some_behavior(self):
    self.widget.bar()
    self.assertEquals(314, self.widget.foo())

在这种情况下,只会调用后一个测试.除了直接解析原始源代码之外,有没有办法以编程方式捕获此类错误?

In this case, only the latter test would get called. Is there a way of programmatically catching this sort of error, short of parsing the raw source code directly?

推荐答案

如果你运行 pylint您的代码,它会在您覆盖另一个方法时通知您:

If you run pylint over your code, it will inform you when you have overwritten another method:

例如,我运行了这个:

class A(object):
    def blah(self):
        print("Hello, World!")

    def blah(self):
        print("I give up!")

这个在线pylint检查器中.除了所有丢失的文档字符串等,我还知道:

In this online pylint checker. Besides all the missing docstrings and such, I get this:

E: 5:A.blah: method already defined line 2

或者,通过命令行:

$ python -m pyflakes .
.\blah.py:5:5 redefinition of unused 'blah' from line 2

这篇关于如何在 Python 类中检测重复的方法名称?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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