我选择的文本编辑器可以通过python插件扩展。它要求我扩展类并覆盖它的方法。一般结构看起来类似下面的代码片段。请注意,函数签名是固定的。变量范围以外的类
ftp_client
应该由两个类的实例共享。
ftp_client = None
class FtpFileCommand(sublime_plugin.TextCommand):
def run(self, args):
global ftp_client # does it reference the variable of the outer scope?
self.ftp_client = ftplib.FTP('foo')
# login and stuff
class FtpFileEventListener(sublime_plugin.EventListener):
def run(self, args):
global ftp_client # same for this
self.ftp_client.quit() #
这两个类都应该有一个共同的变量。为了分享变量,最佳做法是什么?
编辑基于madjars回答:
FtpFileCommand.run
首次调用,instanciates ftp_client
和工程就像一个魅力。稍后调用FtpFileEventListener.run
,完全可以参考ftp_client
,但它仍然是None
。使用全局关键字,是否将变量作为成员添加到self
?
要回答你的编辑第二个问题:做'ftp_client'实例属性违背了使用全局变量的目的。在声明全局优先后,新的'FTP'对象应该分配给'ftp_client'变量。之后,它可以从任何地方被引用,而不需要将其声明为全局的,例如, 'ftp_client.quit()'。 – ekhumoro