Python 为什么pycharm建议把method改成static

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/23554872/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 03:08:19  来源:igfitidea点击:

Why does pycharm propose to change method to static

pythonpycharm

提问by zerkms

The new pycharm release (3.1.3 community edition) proposes to convert the methods that don't work with the current object's state to static.

新的 pycharm 版本(3.1.3 社区版)提议将不适用于当前对象状态的方法转换为静态方法。

enter image description here

在此处输入图片说明

What is the practical reason for that? Some kind of micro-performance(-or-memory)-optimization?

这样做的实际原因是什么?某种微性能(或内存)优化?

回答by Jan Vlcinsky

I can imagine following advantages of having a class method defined as static one:

我可以想象将类方法定义为静态方法的以下优点:

  • you can call the method just using class name, no need to instantiate it.
  • 您只需使用类名即可调用该方法,无需实例化它。

remaining advantages are probably marginal if present at all:

如果存在,剩余的优势可能是微不足道的:

  • might run a bit faster
  • save a bit of memory
  • 可能跑得快一点
  • 节省一点内存

回答by jolvi

PyCharm "thinks" that you might have wantedto have a static method, but you forgot to declare it to be static.

PyCharm“认为”您可能想要一个静态方法,但您忘记将其声明为静态方法。

PyCharm proposes this because the method does not useselfin its body and hence does not actually change the class instance. Hence the method could be static, i.e. callable without having created a class instance before.

PyCharm 提出此建议是因为该方法不在其主体中使用self,因此实际上并未更改类实例。因此,该方法可以是静态的,即无需创建类实例即可调用。

回答by John Worrall

This error message just helped me a bunch, as I hadn't realized that I'd accidentally written my function using my testing example player

此错误消息对我有很大帮助,因为我没有意识到我不小心使用我的测试示例播放器编写了我的函数

my_player.attributes[item] 

instead of the correct way

而不是正确的方法

self.attributes[item]

回答by Don

Since you didn't refer to selfin the barmethod body, PyCharm is asking if you mighthave wanted to make barstatic. In other programming languages, like Java, there are obvious reasons for declaring a static method. In Python, the only real benefit to a static method (AFIK) is being able to call it without an instance of the class. However, if that's your only reason, you're probably better off going with a top-level function - as note here.

由于您没有selfbar方法主体中引用,PyCharm 会询问您是否想要bar静态化。在其他编程语言(如 Java)中,声明静态方法有明显的原因。在 Python 中,静态方法 (AFIK) 的唯一真正好处是无需类的实例即可调用它。但是,如果这是您唯一的原因,那么您最好使用顶级函数 - 如此处所述

In short, I'm not one hundred percent sure why it's there. I'm guessing they'll probably remove it in an upcoming release.

简而言之,我不能百分百确定它为什么在那里。我猜他们可能会在即将发布的版本中将其删除。

回答by Bob Stein

Agreed with @jolvi, @ArundasR, and others, the warning happens on a member function that doesn't use self.

同意@jolvi、@ArundasR 和其他人的意见,警告发生在不使用self.

If you're sure PyCharm is wrong, that the function should not be a @staticmethod, and if you value zero warnings, you can make this one go away two different ways:

如果您确定 PyCharm 是错误的,则该函数不应该是 a @staticmethod,并且如果您重视零警告,则可以通过两种不同的方式使这个警告消失:

Workaround #1

解决方法 #1

def bar(self):
    self.is_not_used()
    doing_something_without_self()

def is_not_used(self):
    pass

Workaround #2[Thanks @DavidP?rsson]

解决方法 #2 [感谢@DavidP?rsson]

# noinspection PyMethodMayBeStatic
def bar(self):
    doing_something_without_self()

The application I had for this (the reason I could not use @staticmethod) was in making a table of handler functions for responding to a protocol subtype field. All handlers had to be the same form of course (static or nonstatic). But some didn't happen to do anything with the instance. If I made those static I'd get "TypeError: 'staticmethod' object is not callable".

我为此的应用程序(我不能使用@staticmethod 的原因)是制作一个处理函数表来响应协议子类型字段。当然,所有处理程序都必须是相同的形式(静态或非静态)。但是有些人没有对实例做任何事情。如果我将这些设为静态,我会得到“TypeError: 'staticmethod' object is not callable”。

In support of the OP's consternation, suggesting you add staticmethod whenever you can, goes against the principlethat it's easier to make code less restrictive later, than to make it more -- making a method static makes it less restrictive now, in that you can call class.f() instead of instance.f().

支持 OP 的惊愕,建议您尽可能添加 staticmethod,这违背了稍后使代码限制更少比使其更多更容易的原则- 使方法静态使其现在限制更少,因为您可以调用 class.f() 而不是 instance.f()。

Guesses as to why this warning exists:

猜测为什么会出现这个警告:

  • It advertises staticmethod. It makes developers aware of something they may well have intended.
  • As @JohnWorrall's points out, it gets your attention when self was inadvertently left outof the function.
  • It's a cue to rethink the object model; maybe the function does not belongin this class at all.
  • 宣传 staticmethod。它让开发人员意识到他们很可能已经打算做的事情。
  • 正如@JohnWorrall 所指出的,当self 无意中被排除在函数之外时,它会引起您的注意。
  • 这是重新思考对象模型的提示;也许这个函数根本不属于这个类。

回答by tlo

I agree with the answers given here (method does not use selfand therefore could be decorated with @staticmethod).

我同意这里给出的答案(方法不使用self,因此可以用 装饰@staticmethod)。

I'd like to add that you maybe want to move the method to a top-level function instead of a static method inside a class. For details see this question and the accepted answer: python - should I use static methods or top-level functions

我想补充一点,您可能希望将该方法移动到顶级函数而不是类中的静态方法。有关详细信息,请参阅此问题和已接受的答案:python - 我应该使用静态方法还是顶级函数

Moving the method to a top-level function will fix the PyCharm warning, too.

将该方法移至顶级函数也将修复 PyCharm 警告。

回答by mincom

I think that the reason for this warning is config in Pycharm. You can uncheck the selection Method may be staticin Editor->Inspection

我认为这个警告的原因是 Pycharm 中的配置。您可以在 Editor->Inspection 中取消选中Method may be static

回答by Junuxx

It might be a bit messy, but sometimes you just don't need to access self, but you would prefer to keep the method in the class and notmake it static. Or you just want to avoid adding a bunch of unsightly decorators. Here are some potential workarounds for that situation.

它可能有点乱,但有时您只是不需要访问self,但您更愿意将方法保留在类中而不是使其成为静态。或者你只是想避免添加一堆难看的装饰器。以下是针对这种情况的一些潜在解决方法。

If your method only has side effects and you don't care about what it returns:

如果您的方法只有副作用并且您不关心它返回的内容:

def bar(self):
    doing_something_without_self()
    return self

If you do need the return value:

如果您确实需要返回值:

def bar(self):
    result = doing_something_without_self()
    if self:
        return result

Now your method is using self, and the warning goes away!

现在您的方法正在使用self,警告消失了!

回答by Junyu Wu

The reason why Pycharm make it as a warning because Python will pass self as the first argument when calling a none static method (not add @staticmethod). Pycharm knows it.

Pycharm 之所以将其作为警告,是因为 Python 在调用非静态方法(而不是添加 @staticmethod)时会将 self 作为第一个参数传递。Pycharm 知道这一点。

Example:

例子:

class T:
    def test():
        print "i am a normal method!"

t = T()
t.test()
output:
Traceback (most recent call last):
  File "F:/Workspace/test_script/test.py", line 28, in <module>
    T().test()
TypeError: test() takes no arguments (1 given)

I'm from Java, in Java "self" is called "this", you don't need write self(or this) as argument in class method. You can just call self as you need inside the method. But Python "has to" pass self as a method argument.

我来自 Java,在 Java 中“self”被称为“this”,你不需要在类方法中写 self(或 this)作为参数。您可以在方法内部根据需要调用 self 。但是 Python “必须”将 self 作为方法参数传递。

By understanding this you don't need any Workaround as @BobStein answer.

通过理解这一点,您不需要任何解决方法作为@BobStein 的回答。