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
  • 相关阅读:
    KVC
    MRC&ARC
    网络基础
    沙盒
    GCD深入了解
    iOS 架构模式MVVM
    iOS 源代码管理工具之SVN
    iOS给UIimage添加圆角的两种方式
    Objective-C 中,atomic原子性一定是安全的吗?
    iOS Block循环引用
  • 原文地址:https://www.cnblogs.com/liujiaxin2018/p/14483280.html
Copyright © 2011-2022 走看看