python入门(15)
多层装饰
def wrapper1(func):
print("进入wrapper1装饰器")
def inner():
print('真正wrapper1执行装饰器')
func()
print("wrapper1装饰完成")
return inner
def wrapper2(func):
print("进入wrapper2装饰器")
def inner():
print('真正wrapper2执行装饰器')
func()
print("wrapper2装饰完成")
return inner
@wrapper2
@wrapper1
def info():
print("这是被装饰的函数")
print("###########")
info()
# 进入wrapper1装饰器
# wrapper1装饰完成
# 进入wrapper2装饰器
# wrapper2装饰完成
##############
# 真正wrapper2执行装饰器
# 真正wrapper1执行装饰器
# 这是被装饰的函数
# 结合性: 从下往上
# 执行行: 从上往下
# info() 等同于
# warpper2(warpper1(info))()
函数传参
def wrapper1(func):
print("进入wrapper1装饰器")
def inner(param):
print('真正wrapper1执行装饰器')
func(param)
print("wrapper1装饰完成")
return inner
def wrapper2(func):
print("进入wrapper2装饰器")
def inner(param):
print('真正wrapper2执行装饰器')
func(param)
print("wrapper2装饰完成")
return inner
@wrapper2
@wrapper1
def info(param):
print('需要传递的参数',param)
print("这是被装饰的函数")
print("###########")
info('asd123')
装饰器工厂函数
#根据参数的不同,会返回不同的装饰器
def factory(param1):
def wrapper(func):
print("装饰器函数工厂的装饰器正在装饰")
def inner():
func()
return inner
return wrapper
# ret_func=factory(1)
# @ret_func
# def info():
# print('info')
@factory(1)
def info():
print('info')
info()
注意点:
- 装饰器不在()
- 装饰器工场需要加(),用来生成装饰器
类装饰器
class Authen(object):
def __call__(self, *args, **kwargs):
pass
pass
a = Authen()
a(0)
print(callable(a))
重写call 方法,可使类是可调用的
class Authen(object):
def __init__(self,func):
self.__func=func
print(func)
def __call__(self, *args, **kwargs):
print("装饰器的装饰功能")
self.__func()
pass
@Authen
def info():
print("info")
info()
文件操作
open的模式
'r' open for reading (default)
'w' open for writing, truncating the file first
'x' create a new file and open it for writing
'a' open for writing, appending to the end of the file if it exists
'b' binary mode
't' text mode (default)
'+' open a disk file for updating (reading and writing)
'U' universal newline mode (deprecated)