您的位置:首页 > 其它

global variable and local variable

2014-04-03 17:42 225 查看
out_list = ['I am the outlist']

def case1():
# out_list is the global varible because it is not assigned in
# the function. It is only referenced
out_list.append('modified in case2')
print('in-case1 print: %s' % out_list)
return

def case2():
# can not use (reference) un-defined variable
inner_list.append('added in case2')
print('in-case2 print: %s' % inner_list)
return

def case3():
# out_list is a local variable here because is assigned
out_list = []
out_list.append('modified in case4')
print('in-case4 print: %s' % out_list)
return

def case4():
# explictly use out_list
global out_list
out_list.append('modified in case3')
print('in-case3 print: %s' % out_list)
return

def case5():
# interestingly, if out_list appears somewhere in function,
# it is treated as a local variable
# This, is because when python is parsing fucntions, it will find
# all the assignment in this function (like out_list = []), if there
# is one, this variable will be treated as local variable
out_list.append('modified in case5')
print('in-case5 print: %s' % out_list)
out_list = []
out_list.append('modified in case5')
print('in-case5 print: %s' % out_list)
return

def case6():
# use global and assign in function again
global out_list
out_list.append('modified in case5')
print('in-case6 print: %s' % out_list)
out_list = []
out_list.append('modified in case5')
print('in-case6 print: %s' % out_list)
return

def case7():
# use global before assignment, the varible is a global variable now!
# then you can print inner_list outside the function
global inner_list
inner_list = []
inner_list.append('modified in case7')
return

if __name__ == '__main__':
case1()
print('out-function print: %s' % out_list)
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: