Discuss / Python / 在__getitem__() 传入的切片参数里加上了step

在__getitem__() 传入的切片参数里加上了step

Topic source

class Fib(object):

    ...:     def __getitem__(self,n):

    ...:         if isinstance(n,int):

    ...:             a,b = 1,1

    ...:             for x in range(n):

    ...:                 a,b = b,a+b

    ...:             return a

    ...:         if isinstance(n,slice):

    ...:             a,b = 1,1

    ...:             L = []

    ...:             start = n.start

    ...:             stop = n.stop

    ...:             step = n.step

    ...:             if start is None:

    ...:                 start = 0

    ...:             if step is None:

    ...:                 step = 1

    ...:             for x in range(stop):

    ...:                 if x >= start:

    ...:                     L.append(a)

    ...:                 a,b = b,a+b

    ...:             return L[0::step]

你最后 return 返回的 L[0::step],我感觉只是在利用切片的功能去实现了切片,等于没有实现加了step的切片效果,真正想要实现加了步数step的切片效果,应该将每step步长所得到的数append进一个新列表L1中,最后返回这个新的列表L1。


  • 1

Reply