對于列表List或者元組Tuple,通過內(nèi)建方法len(),可以得出列表或者元組中元素的個(gè)數(shù)。如果一個(gè)類表現(xiàn)得像一個(gè)list,想使用len()函數(shù)來獲取元素個(gè)數(shù)時(shí),則需要實(shí)現(xiàn)__len__()方法。
比如我們實(shí)現(xiàn)一個(gè)班級Class的類,初始化把班級的同學(xué)名字列表傳進(jìn)去,希望len()函數(shù)可以返回班級同學(xué)的數(shù)量時(shí),可以這樣實(shí)現(xiàn)。
class Class: def __init__(self, students): self.students = students def __len__(self): return len(self.students) students = ['Alice', 'Bob', 'Candy'] class_ = Class(students) len(class_) # ==> 3
通過自定義__len__()方法,可以讓len()函數(shù)返回相關(guān)的結(jié)果,如果沒有定義__len__()方法的類使用len()函數(shù)獲取長度時(shí),將會(huì)引起異常。
class Class: def __init__(self, students): self.students = students class_ = Class(students) len(class_) Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: object of type 'Class' has no len()
斐波那契數(shù)列是由 0, 1, 1, 2, 3, 5, 8...構(gòu)成。
請編寫一個(gè)Fib類,F(xiàn)ib(10)表示數(shù)列的前10個(gè)元素,print Fib(10) 可以打印出數(shù)列的前 10 個(gè)元素,len(Fib(10))可以正確返回?cái)?shù)列的個(gè)數(shù)10。
參考答案:
class Fib(object): def __init__(self, num): self.res = [] self.num = num a = 0 b = 1 for x in range(num): self.res.append(a) a, b = b, a + b def __str__(self): return str(self.res) def __len__(self): return self.num f = Fib(10) print(f) print(len(f))
請驗(yàn)證,完成請求
由于請求次數(shù)過多,請先驗(yàn)證,完成再次請求
打開微信掃碼自動(dòng)綁定
綁定后可得到
使用 Ctrl+D 可將課程添加到書簽
舉報(bào)