[Python] Understand Scope in Python
Python in Scope Understand
2023-09-14 09:00:51 时间
Misunderstanding scope can cause problems in your application. Watch this lesson to learn how Python scope works and the hidden implications it presents. Local scope, nonlocal scope, and global scope variables are demonstrated and explained.
For example, we have the code:
def whoami(): def local_groot(): i = "I am local groot" print(i) #"I am local groot" i = "I am groot" print(i) # "I am groot" # Call the local groot function local_groot() print(i) # "I am groot"
Each function has its scope, won't conflict with outside function scope's variable.
For the case you do want to overwrite:
def whoami(): def local_groot(): i = "I am local groot" print(i) def nonlocal_groot(): nonlocal i i = "I am nonlocal groot" i = "I am groot" print(i) #"I am groot" nonlocal_groot() print(i) #"I am nonlocal groot"
We can use 'nolocal' keyword.
There is also 'global' keyword, but you don't want to use it, it is not good pratice:
def global_groot(): global i i = "I am global groot"
相关文章
- Python爬虫之反爬虫(随机user-agent,获取代理ip,检测代理ip可用性)
- [Python] Use Static Typing in Python 3.6
- python print 打印的数据包含中文,打印报错UnicodeDecodeError: 'gbk' codec can't decode bytes in position 459-460: illegal multibyte sequence解决办法
- Python中第三方库Requests库的高级用法详解
- [Python] Reuse Code in Multiple Projects with Python Modules
- [Python] Manipulate Data with Dictionaries in Python
- [Python] Check for None (Null) in Python
- Member functions in Python
- Python每日一练(20230413)
- python封装代码示例
- 华为OD机试 - 区间交叠问题(Java & JS & Python)
- 会Python要怎么接单兼职?怎么把它作为副业发展呢??
- 成功解决File "f:program filespythonpython36libre.py", line 142, in <modul
- Python入门教程,30分钟玩转Python编程!
- 学好Python能干什么
- Python实现GWO智能灰狼优化算法优化循环神经网络回归模型(LSTM回归算法)项目实战
- Python爬虫:利用aiowebsocket库抓取WebSocket数据
- Python 爬虫
- Import Modules in Python
- 开发报错记录解决(三):编译python出现“SyntaxError: Non-UTF-8 code starting with ‘xcc‘ in file D”的统一解决办法
- python 数据分析学习笔记 (第三章)