在Python 2.7中,可以使用不同的方式来设置全局变量。
def set_global_variable():
global global_var
global_var = "This is a global variable"
set_global_variable()
print(global_var) # 输出:This is a global variable
# global_variables.py
global_var = "This is a global variable"
# main.py
import global_variables
print(global_variables.global_var) # 输出:This is a global variable
global_variables.global_var = "Modified global variable"
print(global_variables.global_var) # 输出:Modified global variable
# global_variables.py
global_vars = {
"global_var1": "This is global variable 1",
"global_var2": "This is global variable 2"
}
# main.py
import global_variables
print(global_variables.global_vars["global_var1"]) # 输出:This is global variable 1
global_variables.global_vars["global_var1"] = "Modified global variable 1"
print(global_variables.global_vars["global_var1"]) # 输出:Modified global variable 1
这些是在Python 2.7中设置全局变量的不同方式。根据具体的需求和场景,选择合适的方式来设置和管理全局变量。
领取专属 10元无门槛券
手把手带您无忧上云