您的位置:首页 > 文旅 > 美景 > 建设工程有限公司是干什么的_中国乐清新闻_青岛seo关键字排名_百度广告点击软件

建设工程有限公司是干什么的_中国乐清新闻_青岛seo关键字排名_百度广告点击软件

2025/2/27 9:35:26 来源:https://blog.csdn.net/Lookontime/article/details/143457717  浏览:    关键词:建设工程有限公司是干什么的_中国乐清新闻_青岛seo关键字排名_百度广告点击软件
建设工程有限公司是干什么的_中国乐清新闻_青岛seo关键字排名_百度广告点击软件

python-15变量作用域

一.说明

什么是作用域?作用域是指变量在代码中可被访问的范围,这个概念在编程中实在太平常了!理解作用域这一概念在解决命名冲突及调试非常重要!

二.作用域解析顺序(LEGB规则)

Python按照以下顺序解析变量的作用域,称为LEGB规则:

  1. Local: 当前函数内部的变量;
  2. Enclosing: 外部函数的局部变量(如果有嵌套函数);
  3. Global: 当前模块中的全局变量;
  4. Built-in: 内置的变量和函数;
x = "global"def outer_function():x = "enclosing"def inner_function():x = "local"print(x)  # 输出: localinner_function()print(x)  # 输出: enclosingouter_function()
print(x)  # 输出: global#################
x = 0def increment():print(x)  def demo():x = 100increment()
demo()      #输出: 0###################
x = 0
def demo():x = 100def increment():nonlocal xprint(x)  increment()
demo()      #输出: 100#################
x = 0
def demo():x = 100def increment():global xprint(x)  increment()
demo()      #输出: 0

三.globalnonlocal

  1. global 关键字:用于在函数内部修改全局变量

    我们先来看卡在python中不使用**global** 关键字

    x = 0def increment():x += 1print(x)  #报错:local variable 'x' referenced before assignment
    increment()
    print(x)  ############
    x = 0def increment():x = 1print(x)  #输出:1
    increment()
    print(x)      #输出:0
    

    我们再看看使用**global** 关键字

    x = 0def increment():global xx += 1increment()
    print(x)  # 输出: 1
    

    这个概念理解了吧!很简单。。

  2. nonlocal 关键字:用于在嵌套函数中修改外部函数的变量

    这个概念也简单,看下面例子

    def outer_function():x = 10def inner_function():nonlocal xx += 5print(x)inner_function()  # 输出: 15print(x)  # 输出: 15outer_function()
    

四.总结

通过以上例子和**global** 、nonlocal 关键字,大家应该能很好的理解这一概念

创作整理不易,请大家多多关注 多多点赞,有写的不对的地方欢迎大家补充,我来整理,再次感谢!

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com