0

有人可以解释为什么在 printfunc 中无法识别 gloabl 变量 x & y,

代码.py

global x
global y

def test(val_x=None,val_y=None)
    x = val_x
    y = val_y
    printfunc()

def printfunc():
   print('x',x)
   print('y',y)

if __name__ = '__main__':
   test(val_x=1,val_y=2)
4

2 回答 2

2

放置在global里面test()

global在函数内部使用,以便我们可以更改全局变量或创建添加到全局命名空间的变量。:

   def test(val_x=None,val_y=None):
        global x
        global y
        x = val_x
        y = val_y
        printfunc()
于 2012-10-04T16:38:20.657 回答
0

The global keyword is used inside code block to specify, that declared variables are global, not local. So move global inside your functions

def test(val_x=None,val_y=None): #you also forgot ':' here
  global x, y
  x = val_x
  y = val_y
  printfunc()

def printfunc():
  global x, y
  print('x',x)
  print('y',y)
于 2012-10-04T16:43:47.860 回答