zoukankan      html  css  js  c++  java
  • python 内嵌函数, 闭包, 函数装饰器

    一.  函数内嵌 闭包

    • 在python中,函数可以作为返回值, 可以给变量赋值.
    • 在python中, 内置函数必须被显示的调用, 否则不会执行.
      #!/usr/bin/env python
      #-*- coding: utf-8 -*-
      
      def foo():
          m = 4
          def bar():
              n = 3
              d = m + n
              return d
          return bar
      
      test = foo()
      print test()
      
      #结果:
      7
      #!/usr/bin/env python
      #-*- coding: utf-8 -*-
      
      def foo():
          m = 4
          def bar():
              n = 3
              m = m + n
              return m
          return bar
      
      test = foo()
      print test()
      
      #结果
      UnboundLocalError: local variable 'm' referenced before assignment
      
      在python2中 把m换成list就不会出现这样的错误,  在python3中,nonlocal 可以解决这个问题, 没搞清楚其中的原理

    二、嵌套函数和它的变种(装饰器)


    以下两端代码,作用是相同的,

    def test(n):
        return n  
    
    def test_pro(func):
        y = 100
        def warpper(x):
            return func(y) * x
    
        return warpper 
    
    f = test_pro(test)
    print f(4)
    
    #结果
    400

    将上边代码改写:

    def test_pro(func):
        y = 100
        def warpper(x):
            return func(y) * x
    
        return warpper
    
    @test_pro
    def test(n):
        return n
    
    print test(4)
    
    #结果
    400
  • 相关阅读:
    docker 部署springboot
    CentOS 7 安装docker
    008自瞄原理
    007根据矩阵基地址绘制方框
    006寻找矩阵
    005分析其他人基地址
    易语言读取鼠标坐标x,y
    003获取鼠标x,y
    Oracle单机Rman笔记[0]---环境准备
    系统优化设计笔记--曹大公众号文章笔记
  • 原文地址:https://www.cnblogs.com/v394435982/p/5193202.html
Copyright © 2011-2022 走看看