python nonlocal 关键字
2021/12/1 14:08:27
本文主要是介绍python nonlocal 关键字,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!
文章目录
- 1.引子
- 2.nonlocal的作用
1.引子
刷题遇到了这个回文链表的题目,其中解答需要用到nonlocal这个关键字,不然在inner function中会显示没有left这个变量
class Solution: def isPalindrome(self, head: ListNode) -> bool: left = head def traverse(right): if not right: return True nonlocal left res = traverse(right.next) res = res and right.val == left.val left = left.next return res return traverse(head)
2.nonlocal的作用
对比两段函数
def myfunc1(): x = "John" def myfunc2(): x = "hello" myfunc2() return x print(myfunc1())
上面这段没有nonlocal, x 在func2中是 local variable, 所以不会改变func1中的x所以输出的是John
def myfunc1(): x = "John" def myfunc2(): nonlocal x x = "hello" myfunc2() return x print(myfunc1())
而这段函数在inner function中有 nonlocal 关键字修饰x,这时在func2中修改x是会使x发生变化的, 所以输出的是hello.
上面引子的例子里, 随着right 的左移, left也要跟着右移, 如果没有nonlocal修饰, 首先会报错找不到left.val, 其次left = left.next也不会改变函数外的left
这篇关于python nonlocal 关键字的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!
- 2024-05-08有遇到过吗?同样的规则 Excel 中 比Python 结果大
- 2024-03-30开始python成长之路
- 2024-03-29python optparse
- 2024-03-29python map 函数
- 2024-03-20invalid format specifier python
- 2024-03-18pool.map python
- 2024-03-18threads in python
- 2024-03-14python Ai 应用开发基础训练,字符串,字典,文件
- 2024-03-13id3 algorithm python
- 2024-03-13sum array elements python