Python 3.5,斐波数列, a,b = 0,1
怪我咯
怪我咯 2017-04-18 10:25:31
0
2
689

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 再回到循环体?

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

怪我咯
怪我咯

走同样的路,发现不同的人生

reply all(2)
迷茫

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.

Peter_Zhu

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.

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template