zoukankan      html  css  js  c++  java
  • python中的内嵌函数

    python允许在函数内部定义另一个函数,这种函数称为内嵌函数或者内部函数。

    1、例

    >>> def a():        ## a外层函数,b为内层函数
        print("hello world!")
        def b():
            print("xxxxx!")
        b()
    
        
    >>> a()
    hello world!
    xxxxx!
    >>> b()         ## 函数b的作用域都在函数a内,别的地方无法调用函数b。
    Traceback (most recent call last):
      File "<pyshell#1032>", line 1, in <module>
        b()
    NameError: name 'b' is not defined
    >>> def a():
        print("hello world!")
        def b():
            print("xxxxxx!")
        return b()
    
    >>> a()
    hello world!
    xxxxxx!
    >>> def a():
        print("hello world!")
        def b():
            print("xxxxxx!")
        return b
    
    >>> a()
    hello world!
    <function a.<locals>.b at 0x000002224043B550>
    >>> a()()
    hello world!
    xxxxxx!

    2、在嵌套函数中,内部函数可以引用外部函数的局部变量

    >>> def a():
        x = 100
        y = 200
        def b():
            print("x value = ",x)
            print("y value = ",y)
        return b()
    
    >>> a()
    x value =  100
    y value =  200

    3、python允许在函数内部定义另一个函数,这种函数称为内嵌函数或者内部函数。

    示例:

    >>> def a(x):
        print("x = ",x)
        def b(y):
            print("y = ",y)
            print("x * y = ",x * y)
        return b
    
    >>> a(3)(8)
    x =  3
    y =  8
    x * y =  24
    >>> a(5)(9)
    x =  5
    y =  9
    x * y =  45
    >>> def a(x):
        print("x = ",x)
        def b(y):
            print("y = ",y)
            print("x + y = ", x + y)
            print("x - y = ", x - y)
            print("x * y = ", x * y)
            print("x / y = ", x / y)
        return b
    
    >>> a(8)(2)
    x =  8
    y =  2
    x + y =  10
    x - y =  6
    x * y =  16
    x / y =  4.0
  • 相关阅读:
    2014年最火的 21个JavaScript 框架
    20个2014年最优秀的PHP框架
    iOS App 研发的最后冲刺:内测与部署
    fir.im Weekly
    Jenkins + GitHub + fir-cli 一行命令从源码到fir.im
    一行命令 优化上传速度
    更新日志
    教你轻松看懂 iOS9 新功能
    fir.im Weekly
    好好干活
  • 原文地址:https://www.cnblogs.com/liujiaxin2018/p/14483280.html
Copyright © 2011-2022 走看看