【发布时间】:2011-12-06 23:10:00
【问题描述】:
我选择的文本编辑器可以通过 python 插件进行扩展。它需要我扩展类并覆盖它的方法。一般结构看起来类似于下面的 sn-p。请注意,函数签名是固定的。
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?
【问题讨论】:
-
回答编辑中的第二个问题:使
ftp_client成为实例属性违背了使用全局变量的目的。新的FTP对象应在首先将其声明为全局变量后分配给ftp_client变量。之后,可以从任何地方引用它,而无需将其声明为全局,例如ftp_client.quit().
标签: python class variables namespaces scope