python练习笔记,装饰器、定制方法生成特定的类
# -*- coding: utf-8 -*-def catch_exception(func): def wrap(self, *args, **kw): try: return func(self, *args, **kw) except Exception: self.revive() print('An Exception raised') return wrapclass Test(object): # 初始化 def __init__(self, path=''): self.__slots__ = ('v1','v2','a') self.__a = 123 self.__b = 456 self.a = 1 self.__path = path # 使用len() def __len__(self): return 100 # 使用迭代 def __iter__(self): # return iter([1,2,3,4]) return self def __next__(self): if self.a < 100: self.a *= 2 return self.a else: raise StopIteration() # 使用数字下表直接访问 def __getitem__(self, n): for i in range(n): self.a *= 2 return self.a # 属性不存在时调用,返回属性/函数 def __getattr__(self, path): # if attr == 'tn': # return 'tttttt' return Test('%s/%s' % (self.__path, path)) def get_path(self): return self.__path def __call__(self, *args, **kw): # for x in args: # print(x) # for k,v in kw.items(): # print('%s = %s' % (k,v)) print(args) print(kw) return '调用自己' # 修饰器 @catch_exception def sum(self): return self.__a + self.__b def revive(self): print('revive from Exception')if __name__ == '__main__': t = Test() for i in Test(): print(i) print(t.sum(), t[10]) print(t.api.football.csl.s2018.get_path()) print(t(123, 'abc',no=1,name='bob'))