本文共 3677 字,大约阅读时间需要 12 分钟。
#!/usr/bin/env python# -*- coding: utf-8 -*-# @Time : 2017/7/26 20:38# @File : Test4.py"""闭包的使用"""def outer(greet): def inner(name): print(greet,name) return innerout = outer('你好')out('小明')
#!/usr/bin/env python# -*- coding: utf-8 -*-# @Time : 2017/7/26 20:38# @File : Test4.py"""闭包的使用"""def outer(greet): def inner(name): print(greet,name) return innerout = outer('你好')print (dir(out))print (out.__closure__)print (type(out.__closure__[0]))print (out.__closure__[0].cell_contents)
E:\Python3\python.exe E:/Python工作空间/model/close/Test4.py['__annotations__', '__call__', '__class__', '__closure__', '__code__', '__defaults__', '__delattr__', '__dict__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__get__', '__getattribute__', '__globals__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__kwdefaults__', '__le__', '__lt__', '__module__', '__name__', '__ne__', '__new__', '__qualname__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__'](,) | 你好Process finished with exit code 0
#!/usr/bin/env python# -*- coding: utf-8 -*-# @Time : 2017/7/26 16:17# @File : Mydemo1.py"""简单装饰器"""import timedef func(func): def say(): print('AOP') func() return say@funcdef Target(): print('start') time.sleep(1) print('end')Target()
#!/usr/bin/env python# -*- coding: utf-8 -*-# @Time : 2017/7/26 16:42# @File : Mydemo2.py"""装饰器检验奇数偶数"""def check(func): def wrapper(a,b): res=func(a,b) if res % 2 == 0: print('偶数') else: print('奇数') return wrapper@checkdef func(a,b): res = a+b return resfunc(1,2)
#!/usr/bin/env python# -*- coding: utf-8 -*-# @Time : 2017/7/26 19:51# @File : Mydemo3.py"""带参数的装饰器"""def check(flag=True): if flag: def _check(func): def wrapper(*args,**kwargs): res = func(*args,**kwargs) if res % 2 == 0: print('偶数') else: print('奇数') return wrapper else: def _check(func): return func return _check@check(True)def func1(a,b): print('执行func1') return a+b@check(False)def func2(a,b): print('执行func2') return a+bfunc1(9,10)func2(9,10)
转载地址:http://ftcqb.baihongyu.com/