关于python:在为全局变量赋值之前引用的局部变量’delete’

local variable 'delete' referenced before assignment for global variable

本问题已经有最佳答案,请猛点这里访问。

我已经在项目开始时设置了一个全局变量delete,就在导入的库的正下方和任何类之前,但是当我有这段代码时:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
def motion_notify_callback(event):
        if (ispymol == True):

            if event.inaxes is ax:      
            x = event.xdata
            y = event.ydata
            x = round(x,0)
            y = round(y,0)
            x = int(x)
            y = int(y)
            coord = (x,y)


            for i in range(0,len(number_list)):

                if (coord == number_list[i]):
                if (delete == True):
                    pymol.cmd.do("delete CurrentCont")
                    delete = False
                pymol.cmd.do("distance CurrentCont, chain"+lc+" and resi"+resi1[i]+" and name CA, chain"+lc+" and resi"+resi2[i]+" and name CA")

                    delete = True

            for i in range(0,len(rres)):
            if (coord == mappingpredcont[i]):
               if (delete == True):
                       pymol.cmd.do("delete CurrentCont")
                       delete =False
               pymol.cmd.do("distance CurrentCont, chain"+lc+" and resi"+predresi1[i]+" and name CA, chain"+lc+" and resi"+predresi2[i]+" and name CA")

                   delete = True

它在为全局变量赋值之前引用了错误的局部变量"delete"我哪里出错了?


您需要在函数开始时将delete定义为global

1
2
3
def motion_notify_callback(event):
   global delete
   .....

您需要告诉python您打算分配给全局变量:

1
2
3
def motion_notify_callback(event):
    global delete
    ...