python 装饰器

# 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则是生成了一个字符串
在此输入正文

 

转载于:https://www.cnblogs.com/liuzh6/p/8910716.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值