标签:
来源:http://andylin02.iteye.com/blog/841604
结论:python的全局变量:int string, list, dic(map) 如果存在global就能够修改它的值。而不管这个global是否是存在于if中,也不管这个if是否能够执行到。
但是,如果没有
- if bGlobal:
- global g_strVal;
int string 将会报错。而list dic(map)是ok的。
-
- import sys
- import os
-
- g_nVal = 0;
- g_strVal = "aaaa";
-
- g_map = {
- "aaa" : "111",
- "bbb" : "222",
- "ccc" : "333",
- "ddd" : "444"
- }
-
- g_ls = [‘a‘, ‘b‘, ‘c‘]
-
- def FixInt(bGlobal = False):
- if bGlobal:
- global g_nVal;
-
- g_nVal = g_nVal + 1;
-
- def FixString(bGlobal = False):
- if bGlobal:
- global g_strVal;
-
-
- g_strVal = g_strVal + ‘b‘;
-
- def FixMap(bGlobal = False):
- if bGlobal:
- global g_map;
-
-
- g_map[‘aaa‘] = ‘aaa__‘ + g_strVal;
- g_map[‘bbb‘] = ‘bbb__‘ + g_strVal;
- g_map[‘ccc‘] = ‘ccc__‘ + g_strVal;
- g_map[‘ddd‘] = ‘ddd__‘ + g_strVal;
-
- def FixList(bGlobal = False):
- if bGlobal:
- global g_ls;
-
- g_ls.append(‘1‘);
-
- def PrintVal(strInfo):
- if strInfo:
- print("==== %s =====" %strInfo);
-
- print("int value:%d" %g_nVal);
- print("string value:%s" %g_strVal);
- print("map value:%s" %g_map);
- print("list value:%s" %g_ls);
- print("\n\n");
-
- if "__main__" == __name__:
-
- PrintVal("The orgin vlaue");
-
- FixInt();
- FixString();
- FixMap();
- FixList();
-
- PrintVal("print all bGlobal = False vlaue");
-
- FixInt(True);
- FixString(True);
- FixMap(True);
- FixList(True);
-
- PrintVal("print all bGlobal = True vlaue");
-
-
-
-
结果:
==== The orgin vlaue =====
int value:0
string value:aaaa
map value:{‘aaa‘: ‘111‘, ‘bbb‘: ‘222‘, ‘ccc‘: ‘333‘, ‘ddd‘: ‘444‘}
list value:[‘a‘, ‘b‘, ‘c‘]
g_nVal src:0
g_nVal dst:1
==== print all bGlobal = False value =====
int value:1
string value:aaaab
map value:{‘aaa‘: ‘aaa__aaaab‘, ‘bbb‘: ‘bbb__aaaab‘, ‘ccc‘: ‘ccc__aaaab‘, ‘ddd‘: ‘ddd__aaaab‘}
list value:[‘a‘, ‘b‘, ‘c‘, ‘1‘]
g_nVal src:1
g_nVal dst:2
==== print all bGlobal = True value =====
int value:2
string value:aaaabb
map value:{‘aaa‘: ‘aaa__aaaabb‘, ‘bbb‘: ‘bbb__aaaabb‘, ‘ccc‘: ‘ccc__aaaabb‘, ‘ddd‘: ‘ddd__aaaabb‘}
list value:[‘a‘, ‘b‘, ‘c‘, ‘1‘, ‘1‘]
python之全局变量的测试
标签:
原文地址:http://www.cnblogs.com/stevenzeng/p/5234878.html