7.函数作用域和匿名函数

1.匿名函数

lambda 需要一个函数,但是又不想费神去命名一个函数

语法:lambda 参数:表达式

例:add = lambda x, y : x+y    add(1,2) # 3

2.函数的作用域

1)函数外不能访问函数内的变量

2)函数内部能够访问函数外部(全局)变量

    x = 1

    def fun():

        print(x)

3)函数内部不能修改外部变量

     x = 1

    def fun():

        x+=1

        print(x) #报错

4)函数内部变量名可以与函数外变量名相同

    x= 1

    print(x,id(x)) #1 139402080

    def fun():

        x=2

        print(x,id(x))

        x+=1

        print(x)

    fun() #2 139402096 \n 3

global和nonlocal

global 全局变量(函数内部声明全局变量后可以修改之)

例:x=123

      def fun():

        global x

        x+=1

        print(x)

      fun() #124

nonlocal 局部变量(嵌套函数中修改上一层函数中的变量)

例:x=123            #fun2中修改fun1的x

      def fun():

        x=456

        def fun2():

            nonloacl x

            x=789

        print(x)

        fun2()

        print(x)

    fun() #依次输出 456 789 123

3.闭包 函数中存在嵌套函数,外层一次调用可返回内层函数

 语法:

   def fun():

      def fun2():

         函数体

         return 返回值2

       return fun2 

例:def fx(x):

         def fy(y):

             return x*y

         return fy

    fx(2)(3) #6

4.递归和回调函数

递归

函数调用函数本身的函数,需要有终止条件。代码较为简洁,但占用内存较多。

例:def factorial(n):  #求n的阶乘,即1*2*...*n

           if(n==1):                                                    

                return 1

           else                                                    

                return n*factorial(n-1)


回调

自身是一个函数,只是传入到另一个函数中供其调用。回调函数不一定会被调用,要看函数的内部逻辑。

例:def boolean(function, flag): #flag为1调用choose,flag为0输出continue

            if flag==1:

                function()

            else 

                print('continue')

        def choose():

            print('回调函数被调用')

        boolean(choose, 1) #回调函数被调用

        boolean(choose, 0) #continue

      

猜你喜欢

转载自blog.csdn.net/weixin_42089175/article/details/80485451
今日推荐