我在代码中创建了一个函数,该函数需要程序中的大量变量和常量。因此,我将global
与变量一起使用,而且确实很长:5行使所有变量成为全局变量...
我正在寻找一种使所有变量易于全局化的新方法! 请帮助我
这是一个令人讨厌的完美例子:
( using pygame here but not important )
def GoWindow(w):
global screen, a, a_max, barPos, barSize, borderColor, bgBar, background, bg_loaded, current_load, a_dif, a_db, a_da, bar_percent, White, Black, Grey, Blue, Dark_Blue, Red, Dark_Red, Green, Dark_Green, Font,... #and it's continue....
if w == 'load' #rest of the fucntion
答案 0 :(得分:0)
虽然我同意注释,即程序的设计可能存在问题,但是如果需要分配给这些变量,则只需声明global
。
x = 5
def print_x():
print(x)
def assign_x():
x = 10
def assign_global_x():
global x
x = 10
print_x() # prints 5
assign_x() # does nothing (only changes the local `x`)
print_x() # prints 5 (the global `x` is still 5)
assign_global_x() # assigns 10 to the global x
print_x() # prints 10 now
即输出是
5
5
10