首页 > 代码库 > Python_装饰器,生成器_干货哦
Python_装饰器,生成器_干货哦
import time
import calendar
import os
# 时间格式熟悉
"""
# 格式化成2016-03-20 11:45:39形式
time01 = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
print()
# 格式化成Sat Mar 28 22:24:24 2016形式
print(time.strftime("%a %b %d %H:%M:%S %Y", time.localtime()))
# 将格式字符串转换为时间戳
a = "Sat Mar 28 22:24:24 2016"
print(time.mktime(time.strptime(a, "%a %b %d %H:%M:%S %Y")))
print(calendar.month(2017, 2))
print(calendar.calendar(2017, 1, 1, 3))
print("*****", calendar.leapdays(2001, 2017))
#返回月份开始的前一天是周几及月份有几天
print("*****", calendar.monthrange(2017, 7))
"""
# 列表操作
"""
def change_mylist(tmpList):
tmpList.append([9, 9, 9])
print(tmpList)
mylist = [1, 3, 4, 6]
change_mylist(mylist)
print(mylist)
"""
# 字符串转字典
"""
a = ‘{"name":"Lucy", "age":10, "tmp":"adssa"}‘
tmpDic = eval(a) #字符串转字典
for i, j in tmpDic.items():
print("39- %s - %s".center(20, "*") % (i, j))
for i in tmpDic:
print("42- {value}".format(value = http://www.mamicode.com/tmpDic[i]).center(20,"*"))
"""
‘‘‘ 装饰器
原则:1、不能修改被装饰的源代码 2、不能修改被装饰函数的调用方式
‘‘‘
# 参数不固定的
‘‘‘
def tmp_timmer(func):
def tmp_warpper(*args, **kwargs):
start_time = time.time() # 函数调用前
print("999".center(20, "-"))
ret = func(*args, **kwargs) # 函数调用
stop_time = time.time() # 函数调用后
print("52 ***** {dif_time}".format(dif_time = (stop_time - start_time)))
return ret
return tmp_warpper
@tmp_timmer
def time_test():
time.sleep(.5)
print("test---01")
time_test()
‘‘‘
# 有参数的函数进行装饰
‘‘‘
def tmp_zhuangshiqi(func):
def tmp_func(x, y):
print("test---02")
ret = func(x, y)
print("666".center(30, "*"), ret)
return (ret - 5)
return tmp_func
@tmp_zhuangshiqi
def time_test(x, y):
print("test---01")
time.sleep(2.3)
return (x + y)
print(" 84 ".center(15, "-"), time_test(3, 3))
‘‘‘
# 高阶函数 -- 函数即变量
‘‘‘ 返回值包含函数名称;把一个函数当作参数传给另一个函数 ‘‘‘
‘‘‘
def tmpFunc(x, y):
print("*******92*")
return x + y
def count_sum(x, func):
print("----96--", func)
return x * func
print(count_sum(4, tmpFunc(1, 1)))
‘‘‘
# 装饰器调用初级
‘‘‘
def wrapper_01(func):
def test_func(*args, **kwargs):
print("****, 函数调用前")
ret = func(*args, **kwargs)
print("****, 函数调用后*****", ret)
if ret is not None:
return ret - 3
else:
return ret
return test_func #返回 test_func 内存地址
@wrapper_01 # 使用装饰器
def test_print():
print("***** 116 ***行")
time.sleep(2.5)
return 0
print(test_print())
@wrapper_01
def test_print02(x, y):
print("***** 124 ***行")
time.sleep(2.5)
return x + y
print(test_print02(3, 5))
‘‘‘
# 装饰器经典案例_装饰器传参,函数传参。。。
"""
username, password = "Allen", "123"
def auth(checktype):
print(" {tmpCheck} ".format(tmpCheck = checktype).center(50,"-"))
def outer_wrapper(func):
def wrapper(*args, **kwargs):
name01 = input("input username:")
password01 = input("input password:")
print(" {check} ".format(check=checktype).center(100, "*"))
if checktype == "A":
if name01 == username and password01 == password:
ret = func(*args, **kwargs)
print("\033[31;1msuccess login!!!! \033[0m")
return ret * 3
else:
exit("\033[33;1musername or password is wrong !\033[0m")
return 0
else:
if name01 == username and password01 == password:
ret = func(*args, **kwargs)
print("\033[35;1msuccess login!!!! --- B \033[0m")
return ret
else:
exit("\033[36;1musername or password is wrong ! ---- B \033[0m")
return 0
return wrapper
return outer_wrapper
@auth(checktype = "A")
def home_page(x, y):
print("登录主页*****")
return x + y
@auth(checktype = "B")
def personal_page():
print("查看个人信息****")
# 函数调用
print("^^^^^^^^^^^", home_page(2, 3))
personal_page()
"""
# 列表生成器: 两种生成方式
"""
# 方式一
#例一
tmpList = [i * 2 for i in range(10)]
print("***** 185 *****", tmpList)
#例二
def del_int(x):
return x % 2
print("****** 196 *****", [del_int(i) for i in range(10)])
#方式二
a = []
for i in range(10):
a.append(2*i)
print("***** 191 *****", a)
"""
# 斐波那契数:1,1, 2, 3, 5, 8, 13, 21, 34....
"""
# 第n个斐波那契数的值
def fib(n):
if n < 2:
return 1
else:
return fib(n - 1) + fib(n - 2)
# 前n个斐波那契数值的和
def sum_fib(n):
sum_tmp = 0
for i in range(n):
sum_tmp += fib(i)
return sum_tmp
input_int = int(input("input 第几个斐波那契数: "))
print(fib(input_int))
print(sum_fib(input_int))
"""
# 生成器详解: yield 关键字
"""
def fib(tmp_max):
n, a, b = 0, 0, 1
while n < tmp_max:
print("**225**", b)
yield b # 把b的值方到fib内了
a, b = b, a + b
n = n + 1
return "程序结束" # 异常的消息
f = fib(10)
# for i in f: # 循环输出生成器生成的内容
# print("231***", i)
# "执行到这个位置后,就记录了改位置, 故下面的while循环不执行了"
while True:
try:
a = next(f)
print("*** 234 ***", a)
except StopIteration as e:
print("抛出异常".center(50, "*"), e.value)
break
"""
# 生成器:单线程下的并行效果
"""
# yield 保存当前状态后返回,
def consumer(name):
print("%s 准备吃包子!" % (name))
while True:
baozi = yield
print("包子[%s]来了, 被[%s]吃了!" % (baozi, name))
# 生产包子
def producer():
c1 = consumer("A")
c2 = consumer("B")
c1.__next__()
c2.__next__()
print("开始做包子啦。。。。")
for i in range(10):
time.sleep(1.0)
print("做了2个包子哦!")
c1.send(i)
c2.send(i)
#调用函数
producer()
"""
Python_装饰器,生成器_干货哦
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。