python學習第十一天,函數,閉包函數,函數名,可迭代對象與迭代器globas()l與locals()

來源:互聯網
上載者:User

標籤:tle   自訂   func   ext   collect   類類型   功能   哪些   變數   

內建函數:

dir(str)或dir(‘alex‘) --->看該類型內建的方法有哪些,返回一個列表

dict.__iter__() 或 iter(dict) --->將可迭代對象轉換為迭代器

iter1.__next__() 或 next(iter1)--->將迭代器裡面的元素一一輸出

globals()

locals()

 

引入模組判斷某個對象是否是可迭代對象,或是迭代器

from collections import Iterator

print(isinstance(‘alex,Iterator))---->判斷是否是迭代器

from collections import Iterable

print(isinstance(‘alex‘,Iterable))--->判斷是否是可迭代對象

 

跳過Bug:

try: #跳過報錯

  pass

expect StopIteration

  pass

 

1.break 打破for迴圈

list1 = [1,2,3]for i in list1:    print(i)    if i == 1:        break

2.函數的理解:

  內建函數

  自訂函數:一般用完即在記憶體中清除,除了閉包函數

    python可以非常靈活地自訂函數,函數可以被多次調用

3.函數名(函數對象)的應用情境:函數名指向函數的記憶體位址,函數名加括弧就是函數的調用

------->函數名是第一類對象

  a.函數名可以作為值,被賦值給另外一個變數(一般調用函數時用)

def func():    passf = funcf()

  b.函數名可以作為函數的參數(在函數中調用另外一個函數用)

def func1():    print(666)def func2(s):    s()func2(func1)

  c.函數名可以當做函數的傳回值(閉包函數時)

def wraaper():    def inner():        print(666)    return innerret = wraaper()ret()

  d.函數名可以當做容器類類型裡面的元素(一次性調用多個函數)

def func1():    print(1)def func2():    print(2)def func3():    print(3)list1 = [func1,func2,func3]for i in list1:    i()

3.閉包函數:

  運用:爬蟲,裝飾器

  

 

 

4.globals()與locals()

  加括弧的叫做函數:globals(),locals()

  不加括弧的叫做屬性global,nonlocal

    區分:

      globals():僅返回全域的和內建的變數,構成一個字典

      local():返回當前位置的變數,構成一個字典  

def func1():    a = 2    b = 3    print(globals())    print(locals())    def inner():        c = 5        d = 6        print(globals())        print(locals())    inner()func1()
def func():    a = 3    b = 4    print(locals())    print(globals())func()a = 1b = 2print(globals())print(locals())

 5.可迭代對象和迭代器(python中一切皆對象)

  可迭代對象的判斷:該對象內建有__iter__方法的,就是可迭代對象

    (str,list,dict,ret,tuple,range())

  迭代器的判斷:該對象內建有__iter__方法,和__next__方法的,就是迭代器

    (控制代碼f)

    1.手動轉換:

list1 = [1,2,3]iter1 = list1.__iter__()print(iter1.__next__())

    2.for迴圈自動轉換

list1 = [1,2,3]for i in list1:    print(i)

      用while迴圈類比for迴圈的的自動轉換過程

list1 = [1,2,3]iter1 = list1.__iter__()while 1:    try:        print(iter1.__next__())    except StopIteration        break

   迭代器的特性:

    1.迭代器在記憶體中開闢一個記憶體位址,每次只取一個值:(可以處理大資料)

       然而可迭代對象在讀取時開闢N個地址,會佔用記憶體

    2.迭代器的取值是單向的,不能倒退,可以有記錄節點的功能

 

python學習第十一天,函數,閉包函數,函數名,可迭代對象與迭代器globas()l與locals()

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.