search

Home  >  Q&A  >  body text

Python 3.5,斐波数列, a,b = 0,1

class Fib(object):

def __getitem__(self, n):
    a, b = 0, 1
    for x in range(n):
        a, b = b, a + b
    return a
    

f = Fib()
f[0] = 0

不解为什么是f[0] = 0

函数是不是直接执行Return 再回到循环体?

初学者还有很多不懂,请多指教,谢谢

怪我咯怪我咯2786 days ago681

reply all(2)I'll reply

  • 迷茫

    迷茫2017-04-18 10:27:31

    Using the subscript value operator []的时候,程序会去访问对象的__getitem__ function.

    f[0] 相当于 f.__getitem__(self, 0)nAssigned value is 0

    a = 0, b = 1
    for x in range(0):   # 这里range(0) 直接跳过
        a, b = b, a + b
    return a             # a = 0

    Sof[0] = 0.

    I don’t know what’s going on, so I debug it step by step and check the documentation.

    reply
    0
  • 天蓬老师

    天蓬老师2017-04-18 10:27:31

    If

    f[0], that is n = 0

    for x in range(n):
        a, b = b, a + b

    The loop body returns directly, so a has not changed and is still 0.

    reply
    0
  • Cancelreply