# -*- coding: utf-8 -*- #python 27 #xiaodeng #http://www.imooc.com/code/6252 #类的专有方法(__len__) #如果一个类表现得像一个list,要获得有多少个元素,就得用len();要让len()函数正常工作,类必须提供一个特殊的方法__len__(),才能返回元素的个数 #案例01 class Fib(): def __init__(self, num): a, b, L = 0, 1, [] for i in range(num): L.append(a) a, b = b, a+b self.numbers = L def __str__(self): return str(self.numbers) def __len__(self): return len(self.numbers) f = Fib(10) print f print len(f) #案例02 class Students(): def __init__(self, *args): self.names = args def __len__(self): return len(self.names) ss = Students('Bob', 'Alice', 'Tim') print len(ss)