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

making a function staticmethod in python is confusing

您好,我有一个使用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_units 不是方法,将其移出 class 并删除未使用的 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))