为什么 PyLint 会警告没有 __init__ ?
我们有许多似乎不需要 __init__ 的 Python 类,将它们初始化为空是完全可以接受的,甚至是更好的选择。 PyLint 似乎认为这是一件坏事。我是否错过了一些关于为什么没有 __init__ 是一种不好的气味的见解?或者我应该压制这些警告并克服它?
We have numerous python classes that do not seem to need __init__
, initialising them empty is either perfectly acceptable or even preferable. PyLint seems to think this is a bad thing. Am I missing some insight into why having no __init__
is a Bad Smell? Or should I just suppress those warnings and get over it?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
你用这些类来做什么?
如果它们只是一组不需要维护任何状态的函数,则不需要 __init__() 但将所有这些函数移动到它们自己的模块中会更有意义。
如果它们确实保持状态(它们有实例变量),那么您可能应该有一个 __init__() 以便可以初始化这些变量。即使您在创建类时从未为它们提供值,定义它们通常也是一个好主意,这样您的方法调用就不会引用可能存在或不存在的实例变量。
话虽这么说,如果您不需要
__init__()
,请随意忽略该警告。编辑:根据您的评论,您似乎对初始化之前引用变量时遇到的 AttributeError 感到满意。这是对类进行编程的完美方法,因此在这种情况下,忽略 PyLint 的警告是合理的。
What are you using these classes for?
If they are just a grouping of functions that do not need to maintain any state, there is no need for an
__init__()
but it would make more sense to just move all of those functions into their own module.If they do maintain a state (they have instance variables) then you should probably have an
__init__()
so that those variables can be initialized. Even if you never provide values for them when the class is created, it is generally a good idea to have them defined so that your method calls are not referencing instance variables that may or may not exist.That being said, if you don't need an
__init__()
, feel free to ignore that warning.edit: Based on your comment, it seems like you are fine with the AttributeError you will get on referencing variables before initialization. That is a perfectly fine way to program your classes so in that case ignoring the warning from PyLint is reasonable.
通常你至少会使用
__init__()
方法来初始化实例变量。如果您不这样做,请务必关闭该警告。Usually you will at least use the
__init__()
method to initialize instance variables. If you are not doing this, then by all means turn off that warning.