如何处理 pylint 消息:警告:方法可以是函数

发布于 2024-08-29 16:36:13 字数 189 浏览 4 评论 0原文

我有一个 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

婴鹅 2024-09-05 16:36:13

如果它根本不涉及类,那么将其移动到函数中是很常见的。

如果它操作类属性,请使用classmethod装饰器:

@classmethod
def spam(cls, ...):
   # cls is the class, you can use it to get class attributes

classmethodstaticmethod(与前者相同,只是该方法不这样做)最近才引入了从第一个参数获取对该类的引用的方法。
这意味着一些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
def spam(cls, ...):
   # cls is the class, you can use it to get class attributes

classmethod and staticmethod (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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文