Python 2.7 在python中创建函数staticmethod令人困惑

Python 2.7 在python中创建函数staticmethod令人困惑,python-2.7,tkinter,pycharm,Python 2.7,Tkinter,Pycharm,嗨,我有一个使用Tkinter编写的GUI,代码模板如下。我的问题是PyCharm在我的函数(def func1,def func2)上警告我它们是静态的。为了消除警告,我将@staticmethod放在函数上方。这是做什么的,有必要吗 # Use TKinter for python 2, tkinter for python 3 import Tkinter as Tk import ctypes import numpy as np import os, fnmatch import tk

嗨,我有一个使用Tkinter编写的GUI,代码模板如下。我的问题是PyCharm在我的函数(def func1,def func2)上警告我它们是静态的。为了消除警告,我将@staticmethod放在函数上方。这是做什么的,有必要吗

# Use TKinter for python 2, tkinter for python 3
import Tkinter as Tk
import ctypes
import numpy as np
import os, fnmatch
import tkFont


class MainWindow(Tk.Frame):

    def __init__(self, parent):
        Tk.Frame.__init__(self,parent)
        self.parent = parent
        self.parent.title('BandCad')
        self.initialize()

    @staticmethod
    def si_units(self, string):

        if string.endswith('M'):
            num = float(string.replace('M', 'e6'))
        elif string.endswith('K'):
            num = float(string.replace('K', 'e3'))
        elif string.endswith('k'):
            num = float(string.replace('k', 'e3'))
        else:
            num = float(string)
        return num



if __name__ == "__main__":
#    main()
    root = Tk.Tk()
    app = MainWindow(root)
    app.mainloop()

您还可以关闭该检查,以便PyCharm不会警告您。首选项->编辑器->检查。请注意,检查出现在JavaScript部分以及Python部分。

关于@staticmethod混淆的说法是正确的。它在Python代码中并不是真正需要的,在我看来几乎不应该被使用。相反,因为si_单位不是一个方法,所以将它移出类并删除未使用的self参数。(实际上,在添加@staticmethod时,您应该这样做;如果将“self”放在左侧,发布的代码将无法正常工作。)

除非一个人在需要使用“self”时忘记了使用它,否则这就是(或至少应该是)PyCharm警告的意图。没有混乱,没有摆弄PyCharm设置

在编写时,您可以使用dict压缩函数并使其易于扩展到其他后缀

def si_units(string):
    d = {'k':'e3', 'K':'e3', 'M':'e6'}
    end = string[-1]
    if end in d:
        string = string[:-1] + d[end]
    return float(string)

for f in ('1.5', '1.5k', '1.5K', '1.5M'): print(si_units(f))

如果您的方法实际上没有引用
self
,PyCharm会向您发出警告
@staticmethod
只是指无法通过实例的方法,通常称为
self
。从您发布的代码中,很难添加任何其他内容。@jornsharpe。谢谢你的评论。我编辑了我的代码。这是否有助于你回答更多信息。不需要更多信息;仅此而已。