Python基础课:装饰器和闭包
#4.装饰器 #闭包 def fx(x): x += 1 def fy(y): return x*y return fy def f1(func): #print('f1 runing') def f2(y): print('f2 runing') return func(y) + 1 return f2 def gun(m): print('gun runing') return m*m #f1(gun) #fg = f1(gun) def fun(m): print('f2 runing') return gun(m) + 1 #fg(1) #fun(1) @f1 def deco(m): print('这是deco') return m*m #这里通过装饰器的作用,实现给deco的返回值加 1 的功能 """ 打个比方,正常人都会穿鞋,但是呢有些人在鞋子里面就会放个增高鞋垫,这个增高鞋垫 不影响穿鞋子,但是呢会让穿的人看上去更高一点,装饰器就像这个增高鞋垫一样, 它不影响函数的正常使用,但是可以给函数增加更多的功能 """ import time def run_time(func): def new_fun(*args,**kwargs): t0 = time.time() print('star time: %s'%(time.strftime('%x',time.localtime())) ) back = func(*args) print('end time: %s'%(time.strftime('%x',time.localtime())) ) print('run time: %s'%(round(time.time() - t0),4) return back return new_fun @run_time def test(): for i in range(1,10): for j in range(1,i+1): print('%dx%d=%2s'%(j,i,i*j),end = ' ') print () class Test_Class: def __init__(self,func): self.func = func def __call__(self): print('类') return self.func @Test_Class def fun_test(): print('这是个测试函数') #fun_test()() #4.类装饰器 class Rectangle: def __init__(self,length,width): self.width = width self.length = length def area(self): #实例方法 areas = self.length * self.width return areas @property #就像访问属性一样访问方法 def fun(self): return self.width*self.length @staticmethod #不用传self def func(): print('staticmethod func') @classmethod def show(cls): print(cls) print('show fun') e = Rectangle(3,4) f = Rectangle(6,8)