3

我正在编写一个 sublime editor 2 插件,并希望它在会话期间记住一个变量。我不希望它将变量保存为文件(它是密码),但希望能够重复运行命令,并且变量可以访问。

我希望我的插件能够像这样工作......

import commands, subprocess

class MyCommand(sublime_plugin.TextCommand):
  def run(self, edit, command = "ls"):
    try:
      thevariable
    except NameError:
      # should run the first time only
      thevariable = "A VALUE"
    else:
      # should run subsequent times
      print thevariable
4

1 回答 1

4

实现此目的的一种方法是将其设为全局变量。这将允许您从任何函数访问该变量。是一个要考虑的堆栈问题。

另一种选择是将其添加到类的实例中。这通常在__init__()类的方法中完成。该方法在类对象被实例化后立即运行。有关此堆栈讨论的更多信息self__init__()请参阅。这是一个基本的例子。

class MyCommand(sublime_plugin.TextCommand):
    def __init__(self, view):
        self.view = view # EDIT
        self.thevariable = 'YOUR VALUE'

这将允许您在创建类对象后访问该变量。像这样的东西MyCommandObject.thevariable。这些类型的变量将持续到调用该方法的窗口关闭。

于 2013-03-25T16:54:15.290 回答