类外的变量范围 [英] Variable scope outside of classes
问题描述
我选择的文本编辑器通过python插件是可扩展的。它需要我扩展类和覆盖它的方法。一般结构看起来类似于下面的代码段。注意函数签名是固定的。
ftp_client
应该由两个类的实例共享。 p>
ftp_client = None
class FtpFileCommand(sublime_plugin.TextCommand):
def run args):
global ftp_client#是否引用外部范围的变量?
self.ftp_client = ftplib.FTP('foo')
#login和stuff
class FtpFileEventListener(sublime_plugin.EventListener):
def run(self,args ):
global ftp_client#this for this
self.ftp_client.quit()#
这两个类都应该有一个共同的变量。根据madjars的回答,
编辑是什么? b
FtpFileCommand.run
首先调用,现在 ftp_client
并且像一个charm。 FtpFileEventListener.run
稍后调用,可以完美地引用 ftp_client
,但它仍然 / code>。使用global关键字,是否将该变量作为成员添加到
self
?
是的,这是全局
的工作原理。
在我看来,因为它在python标准库的一些模块中这样做了( fileinput < a>)。
My text editor of choice is extensible through python plugins. It requires me to extend classes and override its methods. The general structure looks similar the snippet below. Note that the function signature is fixed.
ftp_client
is supposed to be shared by instances of both classes.
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() #
Both of these classes are supposed to have one variable in common. What is the best practice in order to share variables?
Edit based on madjars answer:
FtpFileCommand.run
is called first, instanciates ftp_client
and works like a charm. FtpFileEventListener.run
is called later and, can reference ftp_client
perfectly but it is still None
. Using the global keyword, does it add the variable as a member to self
?
Yep, that's exactly how global
works.
It seems to me you are doing it right, as it's done this way in some modules of the python standard library (fileinput, for example).
这篇关于类外的变量范围的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!