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

 

posted @ 2021-03-04 22:06  小鲨鱼2018  阅读(420)  评论(0编辑  收藏  举报