如何处理 pylint 消息:警告:方法可以是函数
我有一个 python 类并对其运行 pylint 。它给出的一条消息是:
Warning: Method could be a function
这是否告诉我最好将此方法移出类,因为它不使用任何实例变量?
在 C# 中,我会将其设为静态方法。这里最Pythonic的事情是什么?
I have a python class and ran pylint against it. One message it gave was:
Warning: Method could be a function
Is this telling me that it would be better to move this method out of the class because it doesn't use any instance variables?
In C# I would make this a static method. What's the most pythonic thing to do here?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
如果它根本不涉及类,那么将其移动到函数中是很常见的。
如果它操作类属性,请使用
classmethod
装饰器:classmethod
和staticmethod
(与前者相同,只是该方法不这样做)最近才引入了从第一个参数获取对该类的引用的方法。这意味着一些Python程序员习惯于避免静态和类方法。
一些铁杆 Python 程序员会告诉你这些装饰器只会让事情变得复杂;其他一些人(通常是前 C# 或 Java 程序员)会告诉您使用函数不够面向对象。
我认为这只是一个偏好问题。
Moving it to a function is common, if it doesn't touch the class at all.
If it manipulates class attributes, use the
classmethod
decorator:classmethod
andstaticmethod
(which is the same as the former, except that the method doesn't get a reference to the class from its first parameter) have been introduced quite recently.It means that some Python programmers are used to avoid static and class methods.
Some hardcore Python programmers will tell you that these decorators just complicate things; some other people (usually former C# or Java programmers) will tell you that using a function isn't object-oriented enough.
I think it's just a matter of preference.