Python Jython 全局变量使用

标签 python scope jython global

我对 python 全局变量及其正确用法的理解有问题。代码的第一位工作正常,第二位抛出异常“NameError:全局名称'chosen'未定义”。我确信我在这里错过了一些简单的东西,但我看不出它是什么。

我想将监听器与多个事件生成器中的每一个相关联,然后使用 getChoices 方法获取每个生成器所做选择的字典。

#Working code
class Listener1():
  chosen = "0"
  def __init__(self, choice):
    self.choice = choice

  def actionPerformed(self, event):            
    global chosen
    chosen = self.choice

  @staticmethod
  def getChoices():
    return chosen

e1 = Listener1('evt1')
e1.actionPerformed('abc')
print Listener1.getChoices()

失败代码

class Listener2():  
  chosen2 = {'a':-1}
  def __init__(self, choice):
    self.choice = choice
    global chosen2
    chosen2[self.choice] = 'unset'

  def actionPerformed(self, event):
    val = event
    global chosen2
    chosen2[self.choice] = val

  @staticmethod
  def getChoices():
    return chosen2

e2 = Listener2('evt2')
e2.actionPerformed('def')
e3 = Listener2('evt3')
e3.actionPerformed('ghi')
print Listener2.getChoices()

脚注: 如果我将对全局变量 chosen2 的第一个引用移至类定义之前的行而不是之后的行,则 Listener2 类可以正常工作。

感谢以下答案,代码重写为:

class Listener3():
  chosen3 = {}
  def __init__(self, choice):
    self.choice = choice
    if choice is not None:
        self.chosen3[self.choice] = 'unset'

  def actionPerformed(self, event):
    val = event
    self.chosen3[self.choice] = val

  def getChoices(self):
    return self.chosen3

e1 = Listener3('evt1')
e1.actionPerformed('abc')
e2 = Listener3('evt2')
e2.actionPerformed('def')
e3 = Listener3('evt3')

print Listener3(None).getChoices()
{'evt1': 'abc', 'evt2': 'def', 'evt3':'unset'}

除了更加简单之外,现在工作得非常完美。

最佳答案

global 都不符合您的想法。在这两种情况下,chosenchosen2 都是变量,而不是全局变量。

但是当您将 chosen 声明为全局变量并分配给它时,Python 愉快地创建了一个全局变量(与 Listener1.chosen 分开)并存储了您的值(value)。

但是对于 chosen2 你没有给它分配任何东西;您试图将其视为字典,但您没有通过赋值创建变量,因此失败。

您想使用self.chosen2来代替;作为类变量,它将可供 Listener2 的所有实例使用。您还可以使用Listener2.chosen2。对于chosen,可以使用Listener1.chosen来引用它。 global 关键字可以完全删除。

无论如何,将变量声明为全局并不意味着超出我当前的范围。它意味着在模块范围,因此始终在函数、类和方法定义之外。

关于Python Jython 全局变量使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12374176/

相关文章:

java - 使用 JayDeBeApi 连接到 Hive 时出错 - 未找到类

python - 从文件读取时类型错误 :a bytes-like object is required, 而不是 'str'

python - 如何获取距引用点特定距离范围内的一系列随机点并生成xyz坐标

python - 如何正确命名变量以避免在 Python 中出现类似 "Shadows name from outer scope"的警告

python - 从文件夹中的现有 jar 创建类路径

python - 高效处理文本文件中的数据

ruby-on-rails - 请按语法排序 Mongoid Scope

JavaScript 函数通过调用 Element 访问 this

python - Gephi 脚本控制台不显示节点

python - 有没有人在 Grinder 3 的 jython 脚本中成功使用 'yield' 关键字?