python - 类外的变量范围

标签 python class variables namespaces scope

我选择的文本编辑器可以通过 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/

相关文章:

python - 在另一个类中定义一个类并调用父方法

类上的 Python del

vb.net - 将 xdocument 元素(不是元素)作为字符串传递

javascript - 如何在 ruby​​ 中使用 javascript 中的变量?

javascript - 如何更新以编程方式设置的文本区域的输入

python - 如何让 Django 的 Markdown 过滤器将回车转换为 <br/>?

python - 使用 Flask 和 Peewee 进行分页

python - 如何获得 Python 外部库的 omnicompletion?

javascript - 从另一个外部函数调用 mootools 类方法

python - 如何逐行跳过 DataFrame 标签