__len__ 如果一個類表現得像一個list,要獲取有多少個元素,就得用 len() 函數。 要讓 len() 函數工作正常,類必須提供一個特殊方法__len__(),它返回元素的個數。 例如,我們寫一個 Students 類,把名字傳進去: class Students(object): def __init__(self, *args): self.names = args def __len__(self): return len(self.names) 只要正確實現了__len__()方法,就可以用len()函數返回Students實例的“長度”: >>> ss = Students('Bob', 'Alice', 'Tim') >>> print len(ss) 3 任務 斐波那契數列是由 0, 1, 1, 2, 3, 5, 8...構成。 請編寫一個Fib類,Fib(10)表示數列的前10個元素,print Fib(10) 可以打印出數列的前 10 個元素,len(Fib(10))可以正確返回數列的個數10。 ?不會了怎么辦 需要根據num計算出斐波那契數列的前N個元素。 參考代碼: class Fib(object): def __init__(self, num): a, b, L = 0, 1, [] for n in range(num): L.append(a) a, b = b, a + b self.numbers = L def __str__(self): return str(self.numbers) __repr__ = __str__ def __len__(self): return len(self.numbers) f = Fib(10) print f print len(f)
list只能通過append 和 insert來插入元素!!!