网创优客建站品牌官网
为成都网站建设公司企业提供高品质网站建设
热线:028-86922220
成都专业网站建设公司

定制建站费用3500元

符合中小企业对网站设计、功能常规化式的企业展示型网站建设

成都品牌网站建设

品牌网站建设费用6000元

本套餐主要针对企业品牌型网站、中高端设计、前端互动体验...

成都商城网站建设

商城网站建设费用8000元

商城网站建设因基本功能的需求不同费用上面也有很大的差别...

成都微信网站建设

手机微信网站建站3000元

手机微信网站开发、微信官网、微信商城网站...

建站知识

当前位置:首页 > 建站知识

pythonClass:面向对象高级编程__getitem__

官网解释:

创新互联建站专注于企业成都营销网站建设、网站重做改版、富蕴网站定制设计、自适应品牌网站建设、H5高端网站建设商城网站建设、集团公司官网建设、成都外贸网站制作、高端网站制作、响应式网页设计等建站业务,价格优惠性价比高,为富蕴等各大城市提供网站开发制作服务。

  • object.__getitem__(selfkey)

  • Called to implement evaluation of self[key]. For sequence types,the accepted keys should beintegersandslice 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__


分享名称:pythonClass:面向对象高级编程__getitem__
URL分享:http://bjjierui.cn/article/jsjdso.html

其他资讯