Python:全局和更改变量参考

Python: global & change var reference

好的,我一直在做一些测试,所以我需要在每次 运行 方法时检查结果。因为测试不正常。

我做了一个工作正常的例子(不是测试,但行为相同)。在我的测试中结果没有改变,而在示例中它改变了。

示例

def thread():

    global result
    import time
    time.sleep(0.5)
    result = 5/2
    Gtk.main_quit()


import threading
from gi.repository import Gtk
result = None
t = threading.Thread(target=thread, args=())
t.start()
Gtk.main()
print result

OUTPUT: 2

测试

def testSi_Button_clicked(self):

        def thread(button=self.builder.get_object('Si_Button')):

            import time
            global result
            time.sleep(0.5)
            result = self.esci.Si_Button_clicked(button)
            print 'result ' + str(result)
            #Gtk.main_quit()


        import threading

        self.current_window = 'Home_Window' #DO NOT TRY WITH 'Azioni_Window'
        result = None
        t = threading.Thread(target=thread, args=())
        t.start()
        Gtk.main()
        print 'assert'
        print 'result ' + str(result)
        self.assertIsNotNone(result)

OUTPUT:
Home_Window
return true
result True
assert
result None
F
======================================================================
FAIL: testSi_Button_clicked (testC_Esci.tstEsci)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "testC_Esci.py", line 78, in testSi_Button_clicked
    self.assertIsNotNone(result)
AssertionError: unexpectedly None

thread中,global result指的是模块中名为result的模块级变量,其中testSi_Button_clicked(或者更确切地说,class定义 testSi_Button_clicked) 已定义。它不引用您在 testSi_Button_clicked.

中定义的同名局部变量

要修复,使 result 成为可变对象(例如 dict),删除 global result 语句,并让 thread 成为 [= 的闭包13=]。 (在 Python 3 中,您可以使用 nonlocal 关键字来避免这种包装技巧。)

def testSi_Button_clicked(self):

        def thread(button=self.builder.get_object('Si_Button')):
            import time
            time.sleep(0.5)
            result['result'] = self.esci.Si_Button_clicked(button)
            print 'result ' + str(result['result'])
            #Gtk.main_quit()


        import threading

        self.current_window = 'Home_Window' #DO NOT TRY WITH 'Azioni_Window'
        result = {'result': None}
        t = threading.Thread(target=thread, args=())
        t.start()
        Gtk.main()
        print 'assert'
        print 'result ' + str(result['result'])
        self.assertIsNotNone(result['result'])