装饰器 生成器 生成并运行 斐波那契 迭代器 内置函数 json and pickle

                                                                       装饰器 

装饰器:
定义:本质是函数,(装饰其它函数)
就是为了其他函数添加附加功能
原则:1.不能修改被装饰的函数的源代码
2.不能修改被装饰的函数的调用方法
(意思是我把一个男的改为一个女的,但是他不知到)

实现装饰器知识储备:
1.函数的即“变量”
2.高阶函数
3.嵌套函数
高阶高数+嵌套函数==》装饰器

--------------------------------------------------------我是可爱的分割线----------------------------------------------------------------------

# Author:James

###函数据变量

# 错 函数没定义
#def foo():
# print("in the foo")
# bar() 函数
#foo()

# 这是对的
# def bar():
# # print("in the bar")
# # def foo():
# # print("in the foo")
# # bar()
# # foo()

## 这个也行?我知道Java中代码是一行一行往下执行的 , python就是牛逼
# def foo():
# print("in the foo")
# bar()
# def bar():
# print("in the bar")
# foo() 可能是因为FOO这个函数在最后

# 卧槽猜的果然有道理(错)
#def foo():
# print("in the foo")
# bar()
#foo() 可能是FOO这个函数提前结束了所有就找不到BAR了
#def bar():
# print("in the bar")

#匿名函数
#calc = lambda x:x*3
#print(calc(3))

--------------------------------------------------------我是可爱的分割线----------------------------------------------------------------------

# Author:James
#import time
# 高阶函数
# 很绕的一个例子
# def bar():
# print("in the bar")
#
# def test(func):
# print(func)
# func()#加上这个func相当于 func = bar
# test(bar)#内存地址..


# 装饰了
# def bar():
# print("in the bar")
#
# def test(func):#装饰器
# start_time = time.time()
# func()#加上这个func相当于 func = bar 所以就是bar
# stop_time = time.time()
# print("the func run time is %s"%(start_time--stop_time))
#test(bar)#内存地址..
#bar()#附加了一个时间统计时间

--------------------------------------------------------我是可爱的分割线----------------------------------------------------------------------

import time
def bar():
time.sleep(3)
print("in the bar")
def test2(func):
print(func)#func等于bar的内存地址
return func #又返回了bar的内存地址了
#print(test2(bar))#bar传进去 func就等于bar的内存地址了
#t=test2(bar)
#print(t)
#t()#可以
# 用bar来覆盖
bar = test2(bar)
bar()

# Author:James
#嵌套函数

def foo():
print("in the foo")
def bar():
#(在函数中用def定义的就是嵌套)局部变量特性 不可在外部调用
print("in the bar")
bar()
foo()

#这个不叫嵌套
#def test1():
# test2()# 这叫调用不叫嵌套
#test1()

--------------------------------------------------------我是可爱的分割线----------------------------------------------------------------------

# Author:James
import time
user,passwd = 'James','qwe123'
def auth(auth_type):
print("auth里面func里面是什么?:",auth_type)
def outer_wrapper(func):
def wrapper(*args, **kwargs):
print("wrapper func args?", *args, **kwargs)
if auth_type == "local":
username = input("Username:").strip()
password = input("Password:").strip()
if user == username and passwd == password:
print("\033[32;1mUser has passed authentication\033[0m")
res = func(*args, **kwargs) # from home,函数到这里结束
print("---after authenticaion ")
return res
else:
exit("\033[31;1mInvalid username or password\033[0m")
elif auth_type == "ldap":
print("ldap")

return wrapper
return outer_wrapper

def index():
print("welcome to index page")
@auth(auth_type="local") # home = wrapper()
def home():
print("welcome to home page")
return "from home"

@auth(auth_type="ldap")
def bbs():
print("welcome to bbs page")

index()
print(home()) #相当于调用wrapper
bbs()
 
--------------------------------------------------------我是可爱的分割线----------------------------------------------------------------------
# Author:James
import time #时间统计
# def deco(func):#这里要传参
# start = time.time()#开始时间
# func()
# stop = time.time()#结束时间
# print("the func run is %s"%(start-stop))
# def test1():
# print("in the test1")
# def test2():
# time.sleep(3)
# print("in the test2")
# deco(test1)
# deco(test2)

##这就在没动test1和test2的代码情况下加了附属功能

#高阶函数和嵌套
def timer(func):#timer(tset1) func=test1 func=内存地址
def deco(name,age):#也可以用*args **kwargs
start = time.time()#开始时间 func(name,age)#直接运行 run test1 stop = time.time()#结束时间
print("the func run is %s"%(start-stop))
return deco#返回
# @timer#引用timer方法
# def test1():
# time.sleep(3) #睡三秒
# print("in the test1")
@timer# 错 因为test2等于timer(test2)的test2 fanc等于test2
#deoc直接返回内存地址,所以test2=deoc test2()=deoc(),所以要在func里面传参数
def test2(name,age):
print("test2:",name,age)
# test1()
test2("James",22)
 

                                                                                      斐波那契 和生成器 初识异常处理

# Author:James
#斐波那契 和生成器 初识异常处理
def fbnq(max): # 10
n,a,b = 0,0,1
while n < max:# n<10
#print(b)#每次循环就打印b
yield b
a , b = b,a+b
# a,b=1,2
# t =(b,b+a)
#意思是 a=b b+a
n = n + 1
return "done"

#a = fbnq(10)
g = fbnq(6)
while True:
try:
x = next(g)
print("g:",x)
except StopIteration as e:
print("Generator reurn value:", e.value)
break
# print(a.__next__())
# print("这里可以做点事情 可以进进出出")
# print(a.__next__())
# print(a.__next__())
# print(a.__next__())
# print(a.__next__())
# print(a.__next__())
# print(a.__next__())
# print(a.__next__())
# print(a.__next__())
# print(a.__next__())
#
print("=====start loop====")
# for i in a:
# print(i)

# Author:James
# 生成器并运行算
#凡是可作用于for循环的对象都是Iterable类型(迭代器)
# 凡是作用于next()对象的是Iterator类型 惰性的 (成生器)
# 集合数据类型如list dict str 等是Iterable但不是Iterator,不可以通过iter()函数获得一个Iterator对象

--------------------------------------------------------我是可爱的分割线----------------------------------------------------------------------


                                                                                           生成器并运行



import time
def consumer(name):
print("%s 准备吃包子啦!"%name)
while True:
baozi = yield
print("包子来了[%s]来了,被[%s]吃了"%(baozi,name))
# c = consumer("西门鸡鸡")
# c.__next__()
# b1 = "豆沙馅"
# c.send(b1)
# c.__next__()
def producer(naem):
c = consumer("a")#第一步先声明
c2 = consumer("b")
c.__next__()#第二步
c2.__next__()
print("老子开始准备做包子啦!")
for i in range(10):#第三步 循环
time.sleep(1)
print("做了两个包子!")
c.send(i)
c2.send(i)

producer("James")
--------------------------------------------------------我是可爱的分割线----------------------------------------------------------------------

                                                                                             内置函数

# Author:James
#python中自带的函数

# 匿名函数
# def saybi(n):# 样版
# print(n)
# saybi(3)

#pow 什么和什么的多次方

#(lambda n:print(n))(5) #表态的写法

#calc = lambda n:print(n)#这里不可以for,但是可以用if或者三元
#calc(5)

# calc = lambda n:3 if n<5 else n
# print(calc(55))

#filter 过滤
# res = filter(lambda n:n>5,range(10))
# for i in res:
# print(i)

#不可变集合跟元组一样 不可变
#a = frozenset([1,1,1,1,1,1,15,415,4568,1561])

#整个程序的所有变得格式换为K V 的模式
# 高效 折半查找
#print(globals())

#不常用 locals
# def test():
# local = 333
# print(locals())
# test()
# print(locals())
# print(locals().get("local_var"))

# pow 什么是什么的二次方
# round 去一个小数点

#字典是无序的 ,用sorted排序,按K来排序的列表
#value来排序也可以的
#a = {6:2,8:0,1:4,-5:6,99:11,4:22}
#print(sorted(a.items()))
#print(sorted(a.items(),key=lambda x:x[1]))
#print(a)

# zip(拉链)
# a = [1,2,3,4,5]
# b = ["a","b","c","d","e"]
# for i in zip(a,b):
# print(i)

#import decorator
__import__('decorator')
                                        
--------------------------------------------------------我是可爱的分割线----------------------------------------------------------------------                                             顶顶顶

                                                                                         JSON AND PICKLE

实例化

# Author:James
#import json
import pickle
def sayhi(name):
print("hello",name)
info = {
"name":"James",
"age":22,
"func":sayhi

}
f = open("test.text","wb")
pickle.dump(info,f)#f.write(pickle.dumps(info))

f.close()
--------------------------------------------------------我是可爱的分割线----------------------------------------------------------------------    

反实例化

# Author:James
#import json
#json和pickle一样的 区别在调用的时候多了一个S
import pickle
def sayhi(name):
print("hello",name)
f = open("test.text","rb")
#data = pickle.loads(f.read())
data = pickle.load(f)
print(data["func"]("James"))

--------------------------------------------------------我是可爱的分割线----------------------------------------------------------------------   
实例化2
# Author:James
import json

def sayhi(name):
print("hello",name)
info = {
"name":"James",
"age":22,
# "func":sayhi

}
f = open("test2.text","w")
f.write(json.dumps(info))

info["age"]=23
f.write(json.dumps(info))#dumps可以好多次但是loads这可以一次

f.close()
 
--------------------------------------------------------我是可爱的分割线----------------------------------------------------------------------   
反实例化2
# Author:James
import json

f = open("test2.text","r")
data = json.loads(f.read())#dumps可以好多次但是loads这可以一次

print(data["func"]("James"))






猜你喜欢

转载自www.cnblogs.com/JamseStone/p/9293673.html