函数名, 闭包, 迭代器

Posted nacholau

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了函数名, 闭包, 迭代器相关的知识,希望对你有一定的参考价值。

一. 函数名

函数名是一个特殊变量, 加了()可以执行函数. 

函数名的命名规范和变量是一样的. 

 

函数名可以存在列表中lst = [func1, func2], 可作为参数传递给函数func1(func2), 作为函数的返回值return func2, 可以被重新赋值def func(): pass  func = 1 print(func) => 3. 

 

func()()先运行func()再在返回值上加()

 

二. 闭包

闭包: 在内层函数中访问外层函数的局部变量

好处: 保护变量不受外界影响, 可以让变量常驻内存

 

def outer():

    a = 10

    def inner():

        print(a)

    return inner

def outer():
    a = 10
    def inner():
        print(a)
        return 5
    return inner
a = 20
fun = outer() print(fun()) print(a) # 10 # 5 # 20

  

from urllib.request import urlopen

def outer():
    s = urlopen("http://www.xiaohua100.cn/index.html").read()
    def getContent():
        return s
    return getContent

print("爬取内容.....")

qwe = outer()

asd = 1
while 1:
    print(outer()())
    print(asd)
    asd += 1

  经过尝试: 在while1: print(outer()())时, 用第一层函数的变量s被爬虫爬取网页内容赋值时, 且在后面写了qwe = outer()时, 当拔取网线, 会停止输出. 判断为print(outer()())并没有用常驻内存的变量的值, 而是重新获取了变量的值. 与qwe = outer()    print(qwe())时, 直接使用常驻内存的fun = outer()的变量不同. print(outer()())每次运行都会每次都给s赋一次值, 而print(qwe())是执行函数里面的getContent, s的赋值已经在之前的qwe = outer()赋值完了, 执行print(qwe())时, 并没有再给s赋值. 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

三.迭代器

 



以上是关于函数名, 闭包, 迭代器的主要内容,如果未能解决你的问题,请参考以下文章

11 第一类对象 闭包 迭代器

python之函数名,闭包迭代器

函数名 闭包 迭代器

python之函数闭包可迭代对象和迭代器

函数名, 闭包, 迭代器

11.Python迭代器