python函数名的应用、闭包和迭代器

一、函数名的应用(第一类对象)

  函数名是一个变量,但它是一个特殊的变量,与括号配合可以执行函数变量。

  1.函数名的内存地址

def func():
    print("哈哈")
print(func)  #<function func at 0x000002750A7998C8>

  2.函数名可以赋值给其他变量

def func():
    print("哈哈")
print(func)
a = func  #把函数当成一个变量赋值给另一个变量
a()     #函数调用 func()
#<function func at 0x00000211E56198C8>
#哈哈

  3.函数名可以当做容器类的元素

def func1():
    print("哈哈")
def func2():
    print("哈哈")
def func3():
    print("哈哈")
def func4():
    print("哈哈")
lst = [func1,func2,func3]
for i in lst:
    i()
# 哈哈
# 哈哈
# 哈哈
View Code

  4.函数名可以当函数的参数

def func():
    print("吃了么")
def func2(fn):
    print("我是func2")
    fn()
    print("我是func2")
func2(func)        #把函数func当成参数传递给func2的参数fu
# 我是func2
# 吃了么
# 我是func2
View Code

  5.函数名可以当作函数的返回值

 

def func_1():
    print("这里是函数1")
    def func_2():
        print("这里是函数2")
    print("这里是函数1")
    return func_2
fn = func_1()     #执行函数1,函数1返回的是函数2,这时fn指向的就是上面的函数2   
fn()        #执行上面返回的函数
# 这里是函数1
# 这里是函数1
# 这里是函数2
View Code

二、闭包

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

  优点:

        1保护你的变量不受外界影响

        2.可以让变量常驻内存

   写法:

      def outer():

        a = 10

        def inner():

          print(a)

        retunt inner

   判断方法:

def func():
    a = 10
    def inner():
        print(a)
    print(inner.__closure__) # 如果打印的是None. 不是闭包. 如果不是None, 就是闭包

func()

三、迭代器

    使用dir来查看该数据包含了哪些方法

print(dir(str))
#结果
['__add__', '__class__', '__contains__', '__delattr__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__getnewargs__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__iter__', '__le__', '__len__', '__lt__', '__mod__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__rmod__', '__rmul__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', 'capitalize', 'casefold', 'center', 'count', 'encode', 'endswith', 'expandtabs', 'find', 'format', 'format_map', 'index', 'isalnum', 'isalpha', 'isdecimal', 'isdigit', 'isidentifier', 'islower', 'isnumeric', 'isprintable', 'isspace', 'istitle', 'isupper', 'join', 'ljust', 'lower', 'lstrip', 'maketrans', 'partition', 'replace', 'rfind', 'rindex', 'rjust', 'rpartition', 'rsplit', 'rstrip', 'split', 'splitlines', 'startswith', 'strip', 'swapcase', 'title', 'translate', 'upper', 'zfill']
View Code

    用来遍历列表,字符串,元组...等等可迭代对象

    可迭代对象:Iterable,里面有__iter__()可以获取迭代器,没有__next__()

    迭代器:  Iterable,里面有__iter__()可以获取迭代器,还有__next__()

    迭代器的特点:

        1.只能向前

        2.惰性机制

        3.省内存(生成器)

    for循环的内部机制

        1.首先获取到迭代器

        2.使用while循环获取数据

        3.it.__next__()来获取数据

        4.处理异常 try:xxx  except StopIteration:

s = "我是一名小画家"
it = s.__iter__()
while 1:
    try:
        el = it.__next__()
        print(el)
    except StopIteration:
        break
#
#
#
#
#
#
#
View Code

    判断方法:

s = "abc"
it = s.__iter__()
#第一种方法
print("__iter__" in dir(it))  #输出是Ture说明是可迭代对象
print("__next__" in dir(it))  #输出是Ture说明是迭代器
#第二种方法
from collections import Iterable
from collections import Iterator
print(isinstance(it,Iterable))  #判断是不是可迭代对象
print(isinstance(it,Iterator))  #判断是不是迭代器
View Code
原文地址:https://www.cnblogs.com/qq849784670/p/9455752.html