1

我不能改变一个类的值。

这是我的问题:

#!/usr/bin/env python

import pygtk
pygtk.require20()
import gtk

class MyApp(object):
    def __init__(self):
        self.pencere = gtk.Window(gtk.WINDOW_TOPLEVEL)
        self.pencere.connect("delete_event", gtk.main_quit)

        self.b_Up = gtk.Button("UP")
        self.b_Down = gtk.Button("DOWN")
        self.b_Up.connect("pressed", self.ToUp)
        self.b_Down.connect("pressed", self.ToDown)

        self.tablo = gtk.Table(2, 1, False)
        self.tablo.attach(self.b_Up , 0, 1, 0,1)
        self.tablo.attach(self.b_Down, 1, 2, 0, 1 )

        self.pencere.add(self.tablo)

        self.pencere.show_all()
        return

    def ToUp(self, penar  ):
        print "==========ClassUp======= \n" , var_a
        print "@ToUP : " , var_a
        ChangeUp()
        print var_a , "\n=========ClassEndUp========"

    def ToDown(self, penar):
        print "==========ClassDown======= \n", var_a
        print "@ToDown : ", var_a
        ChangeDown()
        print var_a , "\n========ClassEndDown========="

    def main(self):
        gtk.main()

def ChangeUp():
    print "Changing Up : ", var_a
    var_a=["90", "91", "92", "93", "94", "95", "96", "97", "98", "99" ]
    print var_a , "\n================="


def ChangeDown():
    print "Changing Down : " , var_a
    var_a=["0", "1", "2", "3", "4", "5", "6", "7", "8", "9" ]
    print var_a , "\n================="


var_a=["30", "31", "32", "33", "34", "35", "36", "37", "38", "39" ]

app = MyApp()
app.main()

我想在任何地方更改 var_a 列表值当我单击一个按钮时;我收到一条错误消息:

==========ClassDown======= 
['30', '31', '32', '33', '34', '35', '36', '37', '38', '39']
@ToDown :  ['30', '31', '32', '33', '34', '35', '36', '37', '38', '39']
Changing Down : 
Traceback (most recent call last):
  File "aa.py", line 35, in ToDown
    ChangeDown()
  File "aa.py", line 48, in ChangeDown
    print "Changing Down : " , var_a
UnboundLocalError: local variable 'var_a' referenced before assignment

我想通过单击更改 var_a 列表值。不仅在课堂上,无处不在。我尝试使用“全局”,但我不能:((我收到一条错误消息)。

我怎么解决这个问题 ?

UnboundLocalError: local variable 'var_a' referenced before assignment

我不太了解python,我是初学者。所以如果你写代码我会很高兴:) 非常感谢!!

4

1 回答 1

3

您的方法定义了一个名为的新局部变量var_a,该变量隐藏了同名的全局变量。

要修复它,您可以在方法的开头添加一个全局声明:

def ChangeDown():
    global var_a
    print "Changing Down : " , var_a
    var_a=["0", "1", "2", "3", "4", "5", "6", "7", "8", "9" ]
    print var_a , "\n================="

但是,如果可能的话,我建议您不要使用全局变量。考虑改用实例变量。

于 2012-12-23T15:24:52.107 回答