【问题标题】:making a function staticmethod in python is confusing在 python 中创建函数 staticmethod 令人困惑
【发布时间】:2016-02-05 15:39:58
【问题描述】:

您好,我有一个使用 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()

【问题讨论】:

  • 如果您的方法实际上并未引用 self,PyCharm 会向您发出警告。 @staticmethod 只是表示没有通过实例的方法,通常命名为self。从您发布的代码中,很难添加任何其他内容。
  • @jonrsharpe。谢谢你的评论。我编辑了我的代码。这是否有助于为您提供更多信息来回答。
  • 不需要更多信息;就是这样。

标签: python-2.7 tkinter pycharm


【解决方案1】:

您也可以关闭该检查,以免 PyCharm 向您发出警告。首选项 -> 编辑器 -> 检查。请注意,检查出现在 JavaScript 部分以及 Python 部分中。

【讨论】:

    【解决方案2】:

    @staticmethod 令人困惑是对的。 Python 代码中并不真正需要它,而且我认为几乎不应该使用它。相反,由于 si_units 不是方法,请将其移出类并删除未使用的 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))
    

    【讨论】:

      猜你喜欢
      • 2014-10-17
      • 1970-01-01
      • 2020-04-23
      • 2011-04-20
      • 2012-09-22
      • 1970-01-01
      • 1970-01-01
      • 2020-05-17
      • 2013-08-23
      相关资源
      最近更新 更多