• 技术文章 >Python技术 >Python基础教程

    python自由变量是什么

    小妮浅浅小妮浅浅2021-07-26 09:33:23原创5644

    1、自由变量是指未绑定到本地作用域的变量。如果自由变量绑定的值是可变的,变量仍然可以在封闭包中操作。如果是不可变的(数字、字符串等。),在封闭包中重新绑定自由变量会出错。

    def make_averager():
    count = 0
    total = 0
    def averager(new_value):
    count += 1
    total += new_value
    return total / count
    return averager
     
     
    >>> avg = make_averager()
    >>> avg(10)
    Traceback (most recent call last):
    ...
    UnboundLocalError: local variable 'count' referenced before assignment

    2、为了将变量标记为自由变量,可以使用nonlocal语句进行声明,nonlocal语句可以解决。

    def make_averager():
        count = 0
        total = 0
        def averager(new_value):
            nonlocal count, total   # 声明count、total为自由变量
            count += 1
            total += new_value
            return total / count
        return averager

    以上就是python自由变量的介绍,希望对大家有所帮助。更多Python学习指路:python基础教程

    本文教程操作环境:windows7系统、Python 3.9.1,DELL G3电脑。

    专题推荐:python自由变量
    品易云
    上一篇:python变量如何在作用域使用 下一篇:Python中JSON数据如何读取

    相关文章推荐

    • Python变量及其使用• python变量名不区分大小写吗• python变量命名报错是什么原因• python变量不等号是什么• python变量怎么写• python变量不需要声明吗• python变量如何拼接• python变量的概念及定义• python变量的赋值和优势• python变量如何在作用域使用

    全部评论我要评论

    © 2021 Python学习网 苏ICP备2021003149号-1

  • 取消发布评论
  • 

    Python学习网