# python 装饰器
标签(空格分隔): 装饰器
定义:本质是函数,用于装饰器他函数,为其他函数添加附加功能。
原则:
1、不能修改被装饰的函数源代码,
2、不能修改调用方式
一个简单的装饰器例子:
import time
def deco(func):
def wrapper():
start_time= time.time()
func()
end_time = time.time()
print("the func run time %s" %(end_time-start_time))
return wrapper
@deco
def test():
print(" start the test")
time.sleep(3)
print(" end the test")
test()
---输出:
start the test
end the test
the func run time 3.000171661376953
---同时装饰带参和不带参数的函数
import time
def deco(func):
def wrapper(*args,**kwargs):
start_time= time.time()
func(*args,**kwargs)
end_time = time.time()
print("the func run time %s" %(end_time-start_time))
return wrapper
@deco
def test():
print(" start the test")
time.sleep(3)
print(" end the test")
@deco
def test1(a,b):
print(" start the test1")
time.sleep(3)
print("a+b=%s"%(a+b))
print(" end the test1")
test()
test1(4,6)
---输出
start the test
end the test
the func run time 3.000171661376953
start the test1
a+b=10
end the test1
the func run time 3.000171661376953
---
模块导入的4种方式:
import module
from module.xx.xx import xx
from module.xx.xx import xx as rename
from module.xx.xx import *
模块:json
import json
ab=[1,5,3,{'4': 5, '6': 7}]
pstr = json.dumps(ab) #encode
print(pstr)
print(json.loads(pstr)) #decode
输出:
[1, 5, 3, {"4": 5, "6": 7}]
[1, 5, 3, {'4': 5, '6': 7}]
dump:方式
import json
ab=[1,5,3,{'4': 5, '6': 7}]
with open("user_passwd.txt",'w') as fp:
json.dump(ab,fp)
输出到文件:
user_passwd.txt:
[1, 5, 3, {"4": 5, "6": 7}]
load:方式
with open("user_passwd.txt",'r') as fp:
info=json.load(fp)
print(info)
输出:
[1, 5, 3, {'6': 7, '4': 5}]
Encode过程,是把python对象转换成json对象的一个过程,常用的两个函数是dumps和dump函数。两个函数的唯一区别就是dump把python对象转换成json对象生成一个fp的文件流,而dumps则是生成了一个字符串
在此输入正文