fjd*_*ont 7 python variables scope namespaces class
我选择的文本编辑器可以通过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() #
Run Code Online (Sandbox Code Playgroud)
这两个类都应该有一个共同的变量.分享变量的最佳做法是什么?
根据madjars回答编辑:
FtpFileCommand.run被称为第一,instanciates ftp_client和工作就像一个魅力.FtpFileEventListener.run后来被称为,可以ftp_client完美地引用,但它仍然是None.使用global关键字,它是否将变量添加为成员self?
在这段代码中:
global ftp_client # does it reference the variable of the outer scope?
self.ftp_client = ftplib.FTP('foo')
Run Code Online (Sandbox Code Playgroud)
您声明ftp_client为全局变量。这意味着它位于模块级别(例如,您的类所在的位置)。
第二行错了。您想分配给全局变量,但您设置了一个同名的实例属性。
它应该是:
global ftp_client
ftp_client = ftplib.FTP('foo')
Run Code Online (Sandbox Code Playgroud)
但让我建议一种不同的方法。一个常见的做法是把这些东西放在类中,因为它被这个类的所有实例共享。
class FtpFileCommand(sublime_plugin.TextCommand):
ftp_client = None
def run(self, args):
FtpFileCommand.ftp_client = ftplib.FTP('foo')
# login and stuff
Run Code Online (Sandbox Code Playgroud)
请注意,该方法没有使用,self因此它也可能是一个类方法:
class FtpFileCommand(sublime_plugin.TextCommand):
ftp_client = None
@classmethod
def run(cls, args):
cls.ftp_client = ftplib.FTP('foo')
# login and stuff
Run Code Online (Sandbox Code Playgroud)
通过这种方式,您将获得类作为第一个参数,并且可以使用它来访问 FTP 客户端,而无需使用类名。