1. 程式人生 > >python之路-day11-迭代器閉包

python之路-day11-迭代器閉包

 

一 、 函式名的運用

  函式名是一個變數,但它是一個特殊的變數,與括號配合可以執行函式的變數。

  1、函式名的記憶體地址

  

  def func():

    print("呵呵")

  print(func)

  結果:

  <function func at 0x1101e4ea0>

  

  2、函式名可以賦值給其他變數

  def func():

    print("呵呵")

  print(func)

  a = func    # 把函式當成一個變數賦值給另一個變數

  a()      # 函式呼叫 func()

  

  3、函式名可以當做容器類的元素

  def func1():

    print("呵呵")

  def func2():

    print("呵呵")

  def func3():

    print("呵呵")

  def func4():

    print("呵呵")

  lst = [func1, func2, func3]

  for i in lst:

    i()

 

  4、函式名可以當做函式的引數

  

  

  5、函式名可以作為函式的返回值

  

       

 

二、閉包

 1、 什麼是閉包?閉包就是內層函式,對外層函式(非全域性)的變數的引用。叫閉包

  def func1():

    name = "alex"

    def func2():

      print(name)    # 閉包

    func2()

  func1()

  結果:

  alex

    

2、我們可以使用__closure__來檢測函式是否是閉包.使用函式名.__closure__
返回cell就是閉包。返回None就不是閉包
def func1():
name = 'alex'
def func2():
print(name)

func2()
print(func2.__closure__)
func1()
結果:(<cell at 0x00000248D5C77618: str object at 0x00000248D5D07068>,)

 3、如何在函式外邊呼叫內部函式

def outer():

  name = 'alex'

  # 內部函式

  def inner()

    print(name)

  return inner

fn = outer()              # 訪問外部函式,獲取到內部函式的地址

fn()         # 訪問內部函式

 

4、總結

  閉包:在內層函式中引入外層函式的變數

  作用:

    1、保護變數不收侵害

    2、讓一個變數常駐記憶體

 

三、迭代器

   dir() 檢視變數能夠執行的方法(函式)

   Iterator : 迭代器,   __iter__(), __next__()

   Iterable:可迭代的  __iter__()

   for迴圈的流程:

   it = lst.__iter__()

   while 1:

     try:

       el = it.__next__()

             for迴圈的迴圈體

      except StopIteration:

         break

   # 從迭代器中獲取資料的唯一方法: __next__()

   三個特徵:

    1、省記憶體

    2、惰性機制

    3、只能往前。不能退後

 

#  如何判斷一個數據是否是可迭代物件
# 1. dir() -> __iter__ 可迭代的
# dir() -> __next__ 迭代器
# lst = ["秦始皇", "漢武帝", "孝文帝", "隋煬帝", "李世民"]
# print("__iter__" in dir(lst)) # True 可迭代的
# print("__next__" in dir(lst)) # False 不是迭代器
#
# print("__iter__" in dir(int))
# print("__next__" in dir(int))
#
# it = lst.__iter__() # 迭代器
# print("__iter__" in dir(it)) # True 迭代器本身就是可迭代的
# print("__next__" in dir(it)) # True
lst = ["秦始皇", "漢武帝", "孝文帝", "隋煬帝", "李世民"]

# collections 關於集合類的相關操作
# Iterable : 可迭代的
# Iterator : 迭代器

from collections import Iterable, Iterator
print(isinstance(lst, Iterable)) # True
print(isinstance(lst, Iterator)) # False

print(isinstance({1,2,3}, Iterable)) # True, 可以使用for迴圈