我选择的文本编辑器可以通过 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
首先被调用,实例化 ftp_client
并像一个魅力一样工作。 FtpFileEventListener.run
稍后调用,可以完美引用 ftp_client
但它仍然是 None
。使用 global 关键字,是否将变量作为成员添加到 self
?
最佳答案
是的,这正是 global
的工作原理。
在我看来你做得对,因为它在 python 标准库的某些模块(例如 fileinput)中就是这样做的。
关于python - 类外的变量范围,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7754626/