實例List化(__getitem__(),__setitem__()和__delitem__())

實現了__iter__()的實例雖能用於for循環,看似像list,但並不能將其當作list來使用,好比,Fib()[5]仍是報錯
可經過實現__getitem__()方法,;來實現讓實例像list那樣按照下標取出元素app

  實現按下標取元素spa

    class Fib(object):
        def __getitem__(self, n):
            a, b = 1, 1
            for x in range(n):
                a, b = b, a + b
            return a
            
    f = Fib()
    f[0]    #輸出:1
    f[1]    #輸出:1
    f[2]    #輸出:2
    f[3]    #輸出:3
    f[10]    #輸出:89
    f[100]    #輸出:573147844013817084101

 

  實現切片功能code

  __getitem__()傳入的參數多是一個int,也多是一個切片對象slice,所以須要作判斷
  若是把對象當作dict,__getitem__()的參數也多是一個能夠做key的object,例如str對象

    class Fib(object):
        def __getitem__(self, n):
            if isinstance(n, int): # n是索引
                a, b = 1, 1
                for x in range(n):
                    a, b = b, a + b
                return a
            if isinstance(n, slice): # n是切片
                start = n.start
                stop = n.stop
                if start is None:
                    start = 0
                a, b = 1, 1
                L = []
                for x in range(stop):
                    if x >= start:
                        L.append(a)
                    a, b = b, a + b
                return L
            
    f[0:5]    #輸出:[1, 1, 2, 3, 5]
    f[:10]    #輸出:[1, 1, 2, 3, 5, 8, 13, 21, 34, 55]
    #該例沒有對step參數做處理,也沒有對負數做處理,因此,要正確實現一個__getitem__()仍是有不少工做要作的

 

  實現元素的設定與刪除
blog

  與之對應的還有__setitem__()方法和__delitem__()方法,分別用於爲某個元素設值和刪除某個元素
  總之,經過上面的方法,可自定義的類表現得和Python自帶的list、tuple、dict沒什麼區別,這徹底歸功於動態語言的"鴨子類型",不須要強制繼承某個接口繼承

相關文章
相關標籤/搜索