国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 學(xué)院 > 開發(fā)設(shè)計 > 正文

Python之global

2019-11-14 17:09:24
字體:
供稿:網(wǎng)友

 

1  Global

  The global statement and its nonlocal cousin are the only things that are remotely like declaration statements in Python. They are not type or size declarations; they are namespace declarations. The global statement tells Python that a function plans to change one or more global names.

  • Global names are variables assigned at the top level of the enclosing module file.
  • Global names must be declared only if they are assigned within a function.
  • Global names may be referenced within a function without being declared.

  In other Words, global allows us to change names that live outside a def at the top level of a module file.

 

2  Example

  The global statement consists of the keyword global, followed by one or more names separated by commas.

X = 88                         # Global Xdef func():    global X    X = 99                     # Global X: outside deffunc()PRint(X)                       # Prints 99

  

y, z = 1, 2                    # Global variables in moduledef all_global():    global x                   # Declare globals assigned    x = y + z                  # No need to declare y, z: LEGB rule

  x, y, and z are all globals inside the function all_global. y and z are global because they aren’t assigned in the function; x is global because it was listed in a global statement to map it to the module’s scope explicitly. Without the global here, x would be considered local by virtue of the assignment.

 

3  access globals

# thismod.pyvar = 99                              # Global variable == module attributedef local():    var = 0                           # Change local vardef glob1():    global var                        # Declare global (normal)    var += 1                          # Change global vardef glob2():    var = 0                           # Change local var    import thismod                    # Import myself    thismod.var += 1                  # Change global vardef glob3():    var = 0                           # Change local var    import sys                        # Import system table    glob = sys.modules['thismod']     # Get module object (or use __name__)    glob.var += 1                     # Change global vardef test():    print(var)    local();    print(var)    glob1();    print(var)    glob2();    print(var)    glob3()    print(var)

  run and get results

>>> import thismod>>> thismod.test()9999100101102

 


發(fā)表評論 共有條評論
用戶名: 密碼:
驗(yàn)證碼: 匿名發(fā)表
主站蜘蛛池模板: 内乡县| 吉首市| 鹤壁市| 浏阳市| 惠州市| 莒南县| 长汀县| 湘潭市| 忻城县| 奉新县| 肥乡县| 韩城市| 察雅县| 静宁县| 丽水市| 诏安县| 铅山县| 堆龙德庆县| 澜沧| 泸州市| 特克斯县| 方山县| 丰原市| 大新县| 台江县| 纳雍县| 依兰县| 同德县| 新源县| 玛多县| 磐石市| 淮安市| 洛阳市| 康平县| 乡城县| 定襄县| 惠安县| 新余市| 翁源县| 台州市| 广元市|