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 再回到循环体?
初学者还有很多不懂,请多指教,谢谢
走同样的路,发现不同的人生
Using the subscript value operator []的时候,程序会去访问对象的__getitem__ function.
[]
__getitem__
f[0] 相当于 f.__getitem__(self, 0) ,nAssigned value is 0
f[0]
f.__getitem__(self, 0)
n
a = 0, b = 1 for x in range(0): # 这里range(0) 直接跳过 a, b = b, a + b return a # a = 0
Sof[0] = 0.
f[0] = 0
I don’t know what’s going on, so I debug it step by step and check the documentation.
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.
Using the subscript value operator
[]
的时候,程序会去访问对象的__getitem__
function.f[0]
相当于f.__getitem__(self, 0)
,n
Assigned value is 0So
f[0] = 0
.I don’t know what’s going on, so I debug it step by step and check the documentation.
If
f[0], that is n = 0
The loop body returns directly, so a has not changed and is still 0.