Python pylint 的“公共方法太少”消息是什么意思
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14027417/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
What does pylint's "Too few public methods" message mean
提问by monsur
I'm running pylint on some code, and receiving the error "Too few public methods (0/2)". What does this message mean? The pylint docsare not helpful:
我在一些代码上运行 pylint,并收到错误“公共方法太少(0/2)”。这个消息是什么意思?该pylint的文档也没有什么帮助:
Used when class has too few public methods, so be sure it's really worth it.
当类的公共方法太少时使用,所以请确保它真的值得。
采纳答案by Blender
The error basically says that classes aren't meant to juststore data, as you're basically treating the class as a dictionary. Classes should have at least a few methods to operate on the data that they hold.
错误基本上是说类并不意味着只是存储数据,因为你基本上是治疗类作为字典。类应该至少有几个方法来操作它们所持有的数据。
If your class looks like this:
如果你的类看起来像这样:
class MyClass(object):
def __init__(self, foo, bar):
self.foo = foo
self.bar = bar
Consider using a dictionary or a namedtupleinstead. Although if a class seems like the best choice, use it. pylint doesn't always know what's best.
考虑使用字典或 anamedtuple代替。尽管如果一个类看起来是最好的选择,请使用它。pylint 并不总是知道什么是最好的。
Do note that namedtupleis immutable and the values assigned on instantiation cannot be modified later.
请注意,它namedtuple是不可变的,并且在实例化时分配的值以后无法修改。
回答by sage
If you are extending a class, then my suggestion is to systematically disable this warning and move on, e.g., in the case of Celery tasks:
如果您要扩展一个类,那么我的建议是系统地禁用此警告并继续,例如,在 Celery 任务的情况下:
class MyTask(celery.Task): # pylint: disable=too-few-public-methods
"""base for My Celery tasks with common behaviors; extends celery.Task
...
Even if you are only extending a single function, you definitely need a class to make this technique function, and extending is definitely better than hacking on the third-party classes!
哪怕你只是扩展一个功能,你肯定需要一个类来实现这个技术的功能,而且扩展绝对比在第三方类上hack好!
回答by Tomasz Gandor
This is another case of pylint's blind rules.
这是pylint's 盲规则的另一个例子。
"Classes are not meant to store data" - this is a false statement. Dictionaries are not good for everything. A data member of a class is something meaningful, a dictionary item is something optional. Proof: you can do dictionary.get('key', DEFAULT_VALUE)to prevent a KeyError, but there is no simple __getattr__with default.
“类不是用来存储数据的”——这是一个错误的陈述。字典并不是万能的。类的数据成员是有意义的,字典项是可选的。证明:您可以dictionary.get('key', DEFAULT_VALUE)防止 a KeyError,但没有简单__getattr__的默认值。
EDIT - recommended ways for using structs
编辑 - 推荐的使用结构的方法
I need to update my answer. Right now - if you need a struct, you have two great options:
我需要更新我的答案。现在 - 如果你需要一个struct,你有两个很好的选择:
a) Just use attrs
a) 只需使用 attrs
These is a library for that:
这些是一个图书馆:
https://www.attrs.org/en/stable/
https://www.attrs.org/en/stable/
import attr
@attr.s
class MyClass(object): # or just MyClass: for Python 3
foo = attr.ib()
bar = attr.ib()
What you get extra: not writing constructors, default values, validation, __repr__, read-only objects (to replace namedtuples, even in Python 2) and more.
你会得到什么:不编写构造函数、默认值、验证、__repr__、只读对象(替换namedtuples,即使在 Python 2 中)等等。
b) Use dataclasses(Py 3.7+)
b) 使用dataclasses(Py 3.7+)
Following hwjp's comment, I also recommend dataclasses:
根据 hwjp 的评论,我还建议dataclasses:
https://docs.python.org/3/library/dataclasses.html
https://docs.python.org/3/library/dataclasses.html
This is almost as good as attrs, and is a standard library mechanism ("batteries included"), with no extra dependencies, except Python 3.7+.
这几乎和 一样好attrs,并且是标准库机制(“包括电池”),除了 Python 3.7+ 之外没有额外的依赖项。
Rest of Previous answer
上一个答案的其余部分
NamedTupleis not great - especially before python 3's typing.NamedTuple:
https://docs.python.org/3/library/typing.html#typing.NamedTuple- you definitely should check out the "class derived from NamedTuple" pattern.
Python 2 - namedtuplescreated from string descriptions - is ugly, bad and "programming inside string literals" stupid.
NamedTuple不是很好 - 特别是在 python 3 之前typing.NamedTuple:https:
//docs.python.org/3/library/typing.html#typing.NamedTuple- 你绝对应该检查“派生自NamedTuple”模式的类。Python 2 -namedtuples从字符串描述创建 - 丑陋、糟糕,而且“在字符串文字中编程”很愚蠢。
I agree with the two current answers ("consider using something else, but pylint isn't always right" - the accepted one, and "use pylint suppressing comment"), but I have my own suggestion.
我同意当前的两个答案(“考虑使用其他东西,但 pylint 并不总是正确的” - 已接受的答案,以及“使用 pylint 抑制评论”),但我有我自己的建议。
Let me point this out one more time: Some classes are meant justto store data.
让我再次指出这一点:有些类仅用于存储数据。
Now the option to also consider- use property-ies.
现在也考虑选项--使用property-ies。
class MyClass(object):
def __init__(self, foo, bar):
self._foo = foo
self._bar = bar
@property
def foo(self):
return self._foo
@property
def bar(self):
return self._bar
Above you have read-only properties, which is OK for Value Object (e.g. like those in Domain Driven Design), but you can also provide setters - this way your class will be able to take responsibility for the fields which you have - for example to do some validation etc. (if you have setters, you can assign using them in the constructor, i.e. self.foo = fooinstead of direct self._foo = foo, but careful, the setters may assume other fields to be initialized already, and then you need custom validation in the constructor).
上面你有只读属性,这对于值对象是可以的(例如像领域驱动设计中的那些),但你也可以提供设置器 - 这样你的类将能够对你拥有的字段负责 - 例如做一些验证等(如果你有 setter,你可以在构造函数中分配使用它们,即self.foo = foo代替 direct self._foo = foo,但小心,setter 可能假设其他字段已经被初始化,然后你需要在构造函数中进行自定义验证) .
回答by Sean Bradley
It's hard when your boss expects single responsibility principle, but pylint says no. So add a second method to your class so your class violates single responsibility principle. How far you are meant to take single responsibility principle is in the eye the beholder.
当你的老板期望单一责任原则时,这很难,但 pylint 说不。所以在你的类中添加第二个方法,这样你的类就违反了单一职责原则。在旁观者眼里,您打算承担单一责任原则的程度如何。
My fix,
我的修复,
I added an extra method to my class, so it now does 2 things.
我在我的类中添加了一个额外的方法,所以它现在做了两件事。
def __str__(self):
return self.__class__.__name__
I'm just wondering if I need to split my class into 2 separate files now, and maybe modules aswell.
我只是想知道我现在是否需要将我的班级分成 2 个单独的文件,也许还有模块。
problem solved, but not with my colleagues who spend all day arguing the spec, rather than getting on with it, like it's life and death.
问题解决了,但不是和我的同事们整天争论规范,而不是继续下去,就像生死攸关一样。

