博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
python函数调用顺序、高阶函数、嵌套函数、闭包详解
阅读量:4612 次
发布时间:2019-06-09

本文共 1829 字,大约阅读时间需要 6 分钟。

 

一:函数调用顺序:其他高级语言类似,Python 不允许在函数未声明之前,对其进行引用或者调用

错误示范:

def foo():    print 'in the foo'    bar()    foo()报错:in the fooTraceback (most recent call last):  File "
", line 1, in
foo() File "
", line 3, in foo bar()NameError: global name 'bar' is not defined

 

def foo():    print 'foo'    bar()foo() #这里bar还没有定义,这里就执行foo这个函数
def bar():   print 'bar' 报错:NameError: global name 'bar' is not defined

 

正确示范:(注意,python为解释执行,函数foo在调用前已经声明了bar和foo,所以bar和foo无顺序之分)

 

def bar():    print 'in the bar'def foo():    print 'in the foo'    bar()    foo()def foo():    print 'in the foo'    bar()def bar():    print 'in the bar'foo()

 

二:高阶函数

满足下列条件之一就可成函数为高阶函数

  1. 某一函数当做参数传入另一个函数中

  2. 函数的返回值包含n个函数,n>0

     

高阶函数示范:

def bar():    print 'in the bar'def foo(func):    res=func()    return resfoo(bar)

高阶函数的牛逼之处:

def foo(func):    return funcprint 'Function body is %s' %(foo(bar))print 'Function name is %s' %(foo(bar).func_name)foo(bar)()#foo(bar)() 等同于bar=foo(bar)然后bar()bar=foo(bar)bar()

三:内嵌函数和变量作用域:

定义:在一个函数体内创建另外一个函数,这种函数就叫内嵌函数(基于python支持静态嵌套域)

函数嵌套示范:

def foo():    def bar():        print 'in the bar'    bar()foo()# bar()

局部作用域和全局作用域的访问顺序

x=0def grandpa():    # x=1    def dad():        x=2        def son():            x=3            print x        son()    dad()grandpa()

局部变量修改对全局变量的影响

y=10# def test():#     y+=1#     print ydef test():    # global y    y=2    print ytest()print ydef dad():    m=1    def son():        n=2        print '--->',m + n    print '-->',m    son()dad()

 

四:闭包:如果在一个内部函数里,对在外部作用域(但不是在全局作用域)的变量进行引用,那么内部函数就被认为是 closure
def counter(start_num=0):    count=[start_num]    def incr():        count[0]+=1        return count[0]    return incrprint counter()print counter()()print counter()()c=counter()print c()print c()

 

转载于:https://www.cnblogs.com/bkwxx/p/10069502.html

你可能感兴趣的文章
jquery
查看>>
IntelliJ IDEA 中文乱码问题解决办法
查看>>
【文文殿下】网络流24题计划
查看>>
Coursera台大机器学习课程笔记6 -- The VC Dimension
查看>>
Ubuntu 16 04 安装KVM
查看>>
【openlayers】CSS3样式的Popups
查看>>
常用表单及控件测试用例检查点总结
查看>>
UVA5874 Social Holidaying 二分匹配
查看>>
网络流24题 餐巾计划(费用流)
查看>>
Codeforces Round #478 (Div. 2) D Ghosts 会超时的判断两个之间关系,可以用map
查看>>
Redis之Hash
查看>>
mysql 相關
查看>>
支持新版chrome,用webstorm编译形成css和sourcemap,调试sass和less源文件
查看>>
Climbing Stairs
查看>>
用来武装Firebug的十四款Firefox插件
查看>>
几种常用排序算法代码实现和基本优化(持续更新ing..)
查看>>
css样式之超出隐藏
查看>>
python-scrapy框架
查看>>
java.lang.OutOfMemoryError: bitmap size exceeds VM budget
查看>>
Java解惑精炼版(一)
查看>>