练习内容:使用闭包函数模拟类实例
1 __author__ = 'Orcsir' 2 class ClosureInstance: 3 def __init__(self, locals): 4 self.__dict__.update(locals) 5 6 def __len__(self): 7 return self.__dict__["__len__"]() 8 9 10 def Stack(): 11 items = [] 12 13 def push(item): 14 items.append(item) 15 16 def pop(): 17 items.pop() 18 19 def __len__(): 20 return len(items) 21 22 dct = {} 23 for name, value in locals().items(): 24 if callable(value): 25 dct[name] = value 26 27 return ClosureInstance(dct) 28 # Test 29 s = Stack() 30 s.push(10) 31 s.push(20) 32 print(len(s))