Python:global&;更改var参考
好的,我已经做了一些测试,所以每次运行方法时我都需要检查结果。因为测试不正常 我已经做了一个很好的例子(不是测试,而是相同的行为)。在我的测试中,结果不会改变,而在示例中,结果会改变 示例Python:global&;更改var参考,python,unit-testing,global-variables,global,Python,Unit Testing,Global Variables,Global,好的,我已经做了一些测试,所以每次运行方法时我都需要检查结果。因为测试不正常 我已经做了一个很好的例子(不是测试,而是相同的行为)。在我的测试中,结果不会改变,而在示例中,结果会改变 示例 def thread(): global result import time time.sleep(0.5) result = 5/2 Gtk.main_quit() import threading from gi.repository import Gtk
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
在
线程
中,全局结果
指的是模块中名为结果
的模块级变量,在该模块中,testSi_按钮
(或者更确切地说,定义testSi_按钮
)被定义。它不引用与您在testSi\u按钮中定义的同名局部变量
要修复,请将result
设置为可变对象(例如dict
),删除全局结果
语句,并将线程
作为结果
的闭包。(在Python3中,您可以使用nonlocal
关键字来避免这种包装技巧。)
你确定?实际上,“结果”出现在[testSi_Button_clicked]中,并在[def thread]中设置为全局。我应该更改什么?我运行了您的示例代码。它也没有给我打印结果,而不是你输出的2。太棒了,我仍然得到2。有人能告诉我怎么做以及为什么吗?在代码中添加了t.join()
之后,我也得到了2。请看下面我的答案。好的,我来谈谈这个例子。我已经试过了。。但切断全球联系不会有任何结果。在这一变化之前,结果是正确的(2)。修改后的测试仍然不起作用,我在写这篇文章的时候把自己弄糊涂了。删除全局
将使用正确的结果
,直到您尝试分配给它,此时您正在分配给局部变量。我想提到Python3的非本地的
,我认为这在这里是正确的(如果你没有使用Python2的话)。好的,所以使用2.7是不可能的。。我无法相信一种解决方法是使用类似于result\u dict={'result':None}
的方法,并将result\u dict
作为参数传递给thread
,并更新字典中的值。尽管仔细想想,一旦result
是一个可变对象,您可以返回我的原始答案,因为您永远不会分配给result
,只访问它引用的对象。
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'])