python Class:面向对象高级编程 __getitem__
admin
2023-07-23 21:43:29
0

官网解释:

  • object.__getitem__(selfkey)

  • Called to implement evaluation of self[key]. For sequence types, the accepted keys should be integers and slice objects. Note that the special interpretation of negative indexes (if the class wishes to emulate a sequence type) is up to the __getitem__()method. If key is of an inappropriate type, TypeError may be raised; if of a value outside the set of indexes for the sequence (after any special interpretation of negative values), IndexError should be raised. For mapping types, if key is missing (not in the container), KeyError should be raised.

    Note:

    for loops expect that an IndexError will be raised for illegal indexes to allow proper detection of the end of the sequence.


对于Fibonacci数列,当我们想抽取特定位置的值看,那又该怎么做,于是就出来了__getitem__这样的函数。


int、list类型:切片(没有step)

#!/usr/bin/python

# -*- coding: utf-8 -*-


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 = Fib()

print f[0:4]

python Class:面向对象高级编程 __getitem__

print f[9]

python Class:面向对象高级编程 __getitem__

相关内容

热门资讯

念念不忘“未获支持”,特朗普又... 【环球网报道 记者 闫珮云】综合美国《纽约邮报》、俄罗斯卫星通讯社、土耳其阿纳多卢通讯社等媒体报道,...
立陶宛叫停与台当局合作,此前疯... 曾经冲在“反华”最前线的立陶宛,如今态度似乎发生变化。立陶宛外交部22日证实,叫停了与台湾当局的合作...
李四川推敬老卡现金化争老年选票 据凤凰卫视报道,台湾年底县市长选举,竞争最为激烈的新北市蓝绿选情胶着。国民党新北市长参选人李四川勤跑...
央视网评:在“人均985”的“... 这两天,全国各省高考分数陆续公布。新闻里、热搜榜再次被高分学霸淡定查分视频或“700+”喜报霸屏霸榜...
鲁比奥:伊朗收费若成先例,将像... 据美国哥伦比亚广播公司(CBS)援引法新社报道,美国国务卿鲁比奥周四警告称,如果允许伊朗对通过霍尔木...
恐慌之下,有妈妈把纸尿裤塞进了... 6月22日下午两点,济南蝉声轰鸣。山东省第一医科大学附属省立医院门诊大厅里,人流如常。“我不回答。”...
凤凰连线在委华人:委内瑞拉首都... 在委内瑞拉连续强震之后,当地有大量房屋倒塌或受损,而首都加拉加斯的民众也都从建筑物中撤离,在户外避险...
1198.79亿元!宇通客车连... 6月24日,世界品牌实验室发布2026年《中国500最具价值品牌》榜单,宇通客车以1198.79亿元...
活力中国调研行|数据多跑路,居... 【大河财立方 记者 夏晨翔 洪昊旸 雄安新区报道】 儿童活动区里,家长正带着孩子嬉戏玩耍;图书馆里,...
公安部公布4起非法占用农用地典... 6月25日,公安部公布4起非法占用农用地典型案例,旨在依法严厉打击非法占用农用地犯罪,全力守护国家粮...