程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式師世界 >> 編程語言 >  >> 更多編程語言 >> Python

Python keywords global and nonlocal

編輯:Python
# global
# 1、 Declare in the local scope ( establish ) A global variable 
name = 'hello'
def func1():
name = 'ait'
print(name) # ait
func1()
print(name) # hello
def func1():
global name1
name1 = 'ait'
print(name1) # ait
func1()
print(name1) # ait
# 2、 Modify global variables 
count = 1
def func3():
global count
count += 1
return count
print(func3()) # 2
# nonlocal
# 1、 Cannot manipulate global variables 
""" count = 1 def func3(): nonlocal count count += 1 return count print(func3()) # Report errors """
# 2、 Local scope : The inner function modifies the local variables of the outer function .
""" def wrapper(): count = 1 def inner(): count += 1 # Report errors , Local can only reference global variables , Do not modify ; A small scope can only refer to a large scope , Do not modify inner() wrapper() """
def wrapper():
count = 1
def inner():
nonlocal count
count += 5
inner()
return count
print(wrapper()) # 6

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式師世界 All Rights Reserved