zoukankan      html  css  js  c++  java
  • python局部函数

    前面所看到的函数都是全局范围内定义的,他们都是全局函数。python还支持在函数体内定于函数,这种被放在函数体内定义的函数称为局部函数

    在默认情况下,局部函数对外部是隐藏的,局部函数只能在其封闭(enclosing)函数内有效,其封闭函数也可以返回局部函数,以便程序在其他作用域中使用局部函数。

    >>> def ca(type,nn):
        def square(n):
            return n*n
        def cube(n):
            return n*n*n
        def fac(n):
            result=1
            for i in range(2,n+1):
                result *=i
            return result
        if type == 'square':
            return square(nn)
        elif type == 'cube':
            return cube(nn)
        else:
            return fac(nn)
    
            
    >>> ca('square',3)
    9
    >>> ca('cube',3)
    27

      >>> ca('',3)
      6
      >>> ca('',4)
      24
      >>> ca('3',3)
      6

    局部函数内的变量也会遮蔽它所在函数内的局部变量:
    >>> def foo():
        name='bob'
        def bar():
            print(name)
            name='jeff'
        bar()
    
    >>> foo()
    Traceback (most recent call last):
      File "<pyshell#174>", line 1, in <module>
        foo()
      File "<pyshell#173>", line 6, in foo
        bar()
      File "<pyshell#173>", line 4, in bar
        print(name)
    UnboundLocalError: local variable 'name' referenced before assignment
    View Code

    python提供了nonlocal关键字,通过nonlocal语句即可声明访问赋值语句只是访问该函数所在函数的局部变量。

    >>> def foo():
        name='bob'
        def bar():
            nonlocal name
            print(name)
            name='jeff'
        bar()
    
        
    >>> foo()
    bob
    View Code

    nonlocal和global功能大致相似,区别只是global用于声明全局变量,而nonlocal用于声明当前函数所在函数的局部变量

  • 相关阅读:
    策略模式精讲
    工厂模式精讲
    单例模式精讲
    原型模式精讲
    CoreJava学习第五课 --- 进入第二阶段:面向对象编程思想
    CoreJava学习第四课-数组
    CoreJava学习第三课
    CoreJava学习第一课
    Oracle练习题一
    JDBC第一课-简介及开发第一个JDBC程序
  • 原文地址:https://www.cnblogs.com/inuyashalove/p/12752023.html
Copyright © 2011-2022 走看看