詳解Python中的__getitem__方法與slice對象的切片操作

來源:互聯網
上載者:User
Fib執行個體雖然能作用於for迴圈,看起來和list有點像,但是,把它當成list來使用還是不行,比如,取第5個元素:

>>> Fib()[5]Traceback (most recent call last): File "", line 1, in TypeError: 'Fib' object does not support indexing

要表現得像list那樣按照下標取出元素,需要實現__getitem__()方法:

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

slice對象與__getitem__

想要使類的執行個體像列表一樣使用下標, 可以設定__getitem__方法。比如:

class _List(object):  def __getitem__(self, key):    print keyl = _List()l[3]  # print 3

但是如果想要使用切片操作的

l[1:4] # print slice(1, 4, None)

會建立一個slice對象用於切片, 可以通過help(slice)查看具體操作。

a = slice(1, 4, None)range(5)[a] # print [1, 2, 3]

更加豐富的操作

class _List(object):    def __init__(self, _list):    self._list = _list  def __getitem__(self, key):    if isinstance(key, int):      return self._list[key]    elif isinstance(key, slice):      reutrn self.__class__(self._list[key])if __name__ == '__main__':  c = _List(range(10))  b = c[1:5]  print b[3] # print 4

如果key是一個整形的話就返回列表元素,如果是一個slice對象的話,就建立一個執行個體並返回。

  • 聯繫我們

    該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.