網站首頁 編程語言 正文
python引用變量的順序: 當前作用域局部變量->外層作用域變量->當前模塊中的全局變量->python內置變量
1.nonlocal
nonlocal關鍵字用來在函數或其他作用域中使用外層(非全局)變量。
首先:要明確 nonlocal
關鍵字是定義在閉包里面的。
請看以下代碼:
x = 0 def outer(): ? ? x = 1 ? ? def inner(): ? ? ? ? x = 2 ? ? ? ? print("inner:", x) ? ? inner() ? ? print("outer:", x) outer() print("global:", x)
結果:
# inner: 2
# outer: 1
# global: 0
現在,在閉包里面加入nonlocal關鍵字進行聲明:
x = 0 def outer(): ? ? x = 1 ? ? def inner(): ?? ??? ?nonlocal x ? ? ? ? x = 2 ? ? ? ? print("inner:", x) ? ? inner() ? ? print("outer:", x) outer() print("global:", x)
結果:
# inner: 2
# outer: 2
# global: 0
看到區別了么?這是一個函數里面再嵌套了一個函數。當使用 nonlocal
時,就聲明了該變量不只在嵌套函數inner()
里面才有效, 而是在整個大函數里面都有效。
2.global
global
關鍵字用來在函數或其他局部作用域中使用全局變量。但是如果不修改全局變量也可以不使用global
關鍵字。
還是一樣,看一個例子:
x = 0 def outer(): ? ? x = 1 ? ? def inner(): ? ? ? ? global x ? ? ? ? x = 2 ? ? ? ? print("inner:", x) ? ? inner() ? ? print("outer:", x) outer() print("global:", x)
結果:
# inner: 2
# outer: 1
# global: 2
global
是對整個環境下的變量起作用,而不是對函數類的變量起作用。
原文鏈接:https://www.cnblogs.com/brad1994/p/6533267.html
相關推薦
- 2023-02-26 Go實現簡單的數據庫表轉結構體詳解_Golang
- 2022-09-26 利用QDir實現刪除選定文件目錄下的空文件夾_C 語言
- 2022-10-20 Flutter實現矩形取色器的封裝_Android
- 2023-02-02 C語言中的冒泡排序問題_C 語言
- 2022-09-28 C++List容器常用函數接口刨析_C 語言
- 2022-05-10 oracle如何創建或刪除臨時表空間和空間詳解
- 2023-01-18 淺析Python的對象拷貝和內存布局_python
- 2022-08-16 hive數據倉庫新增字段方法_數據庫其它
- 最近更新
-
- window11 系統安裝 yarn
- 超詳細win安裝深度學習環境2025年最新版(
- Linux 中運行的top命令 怎么退出?
- MySQL 中decimal 的用法? 存儲小
- get 、set 、toString 方法的使
- @Resource和 @Autowired注解
- Java基礎操作-- 運算符,流程控制 Flo
- 1. Int 和Integer 的區別,Jav
- spring @retryable不生效的一種
- Spring Security之認證信息的處理
- Spring Security之認證過濾器
- Spring Security概述快速入門
- Spring Security之配置體系
- 【SpringBoot】SpringCache
- Spring Security之基于方法配置權
- redisson分布式鎖中waittime的設
- maven:解決release錯誤:Artif
- restTemplate使用總結
- Spring Security之安全異常處理
- MybatisPlus優雅實現加密?
- Spring ioc容器與Bean的生命周期。
- 【探索SpringCloud】服務發現-Nac
- Spring Security之基于HttpR
- Redis 底層數據結構-簡單動態字符串(SD
- arthas操作spring被代理目標對象命令
- Spring中的單例模式應用詳解
- 聊聊消息隊列,發送消息的4種方式
- bootspring第三方資源配置管理
- GIT同步修改后的遠程分支