重新分配全局变量

时间:2017-03-28 00:57:47

标签: sublimetext2 sublimetext3 sublimetext sublime-text-plugin

如何将变量globvar0更新为1

import sublime_plugin

class TestMe(sublime_plugin.EventListener):
    def on_activated(self, view):

        globvar = 0          # The goal is to update this var from 0 to 1

        def updateme():
            global globvar
            globvar = 1

        def printme():
            print(globvar)

        updateme()
        printme()            # It *should* print 1

此代码段(all credits to Paul Stephenson)应打印1。实际上,当我在在线Python游乐场中测试它时,它会起作用,例如here

但由于某种原因,在Sublime(ST3 build 3126)中它打印0。很奇怪。如何解决?

1 个答案:

答案 0 :(得分:1)

你的问题不是在Sublime中这种方式有所不同,你所写的内容在语义上与你基于它的示例代码不同。

在您的代码示例中,globvar并非全局;它是on_activated方法的局部变量。

当您在global globvar函数中说updateme时,您告诉python访问globvar应该是全局变量而不是它当前可以看到的变量来自本地范围,这使它实际上创建一个具有该名称的全局变量,并使用它来代替。

对你而言,这意味着updateme函数正在创建一个全局变量并将其值设置为1,但printme函数正在打印变量的本地版本,该变量仍为0,这就是你所看到的。

要使变量实际上是全局变量,您需要将其移出方法之外的模块文件的顶层:

import sublime_plugin

# Out here the variable is actually "global"
globvar = 0

class TestMe(sublime_plugin.EventListener):
    def on_activated(self, view):    
        def updateme():
            global globvar
            globvar = 1

        def printme():
            print(globvar)

        updateme()
        printme()            # Now prints one
相关问题