• global variable and local variable


     1 out_list = ['I am the outlist']
     2 
     3 def case1():
     4     # out_list is the global varible because it is not assigned in
     5     # the function. It is only referenced
     6     out_list.append('modified in case2')
     7     print('in-case1 print: %s' % out_list)
     8     return
     9 
    10 
    11 def case2():
    12     # can not use (reference) un-defined variable
    13     inner_list.append('added in case2')
    14     print('in-case2 print: %s' % inner_list)
    15     return
    16 
    17 
    18 def case3():
    19     # out_list is a local variable here because is assigned
    20     out_list = []
    21     out_list.append('modified in case4')
    22     print('in-case4 print: %s' % out_list)
    23     return
    24     
    25 
    26 def case4():
    27     # explictly use out_list
    28     global out_list
    29     out_list.append('modified in case3')
    30     print('in-case3 print: %s' % out_list)
    31     return
    32 
    33 
    34 def case5():
    35     # interestingly, if out_list appears somewhere in function,
    36     # it is treated as a local variable
    37     # This, is because when python is parsing fucntions, it will find
    38     # all the assignment in this function (like out_list = []), if there
    39     # is one, this variable will be treated as local variable
    40     out_list.append('modified in case5')
    41     print('in-case5 print: %s' % out_list)
    42     out_list = []
    43     out_list.append('modified in case5')
    44     print('in-case5 print: %s' % out_list)
    45     return
    46 
    47 
    48 def case6():
    49     # use global and assign in function again
    50     global out_list
    51     out_list.append('modified in case5')
    52     print('in-case6 print: %s' % out_list)
    53     out_list = []
    54     out_list.append('modified in case5')
    55     print('in-case6 print: %s' % out_list)
    56     return
    57 
    58 
    59 def case7():
    60     # use global before assignment, the varible is a global variable now!
    61     # then you can print inner_list outside the function
    62     global inner_list
    63     inner_list = []
    64     inner_list.append('modified in case7')
    65     return
    66 
    67 
    68 if __name__ == '__main__':
    69     case1()
    70     print('out-function print: %s' % out_list)
  • 相关阅读:
    Git-远程版本库
    Git-Git分支
    Git-Git里程碑
    Git-冲突解决
    Git-Git库管理
    Git-Git克隆
    Git-改变历史
    Git-历史穿梭
    RHCE考试
    RHCSA考试
  • 原文地址:https://www.cnblogs.com/bluecoffee/p/3643549.html
Copyright © 2020-2023  润新知