1. 程式人生 > >裝飾器 生成器 生成並運行 斐波那契 叠代器 內置函數 json and pickle

裝飾器 生成器 生成並運行 斐波那契 叠代器 內置函數 json and pickle

text dict 過濾 else 聲明 item **kwargs nbsp fun

裝飾器

裝飾器:
定義:本質是函數,(裝飾其它函數)
就是為了其他函數添加附加功能
原則: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"))






裝飾器 生成器 生成並運行 斐波那契 叠代器 內置函數 json and pickle