日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程语言 > python >内容正文

python

W4_python_decorator_generator_Iteratable_Iterator_json_pickle

發(fā)布時間:2023/12/10 python 60 豆豆
生活随笔 收集整理的這篇文章主要介紹了 W4_python_decorator_generator_Iteratable_Iterator_json_pickle 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

W4_python_decorator_generator_Iteratable_Iterator

  • 50.第03章節(jié)-Python3.5-裝飾器詳解
  • 51.第04章節(jié)-Python3.5-裝飾器應用詳解
  • 52.第05章節(jié)-Python3.5-裝飾器之函數即變量
  • 53.第06章節(jié)-Python3.5-裝飾器之高階函數
  • 54.第07章節(jié)-Python3.5-裝飾器之嵌套函數
  • 55.第08章節(jié)-Python3.5-裝飾器之案例剖析1
  • 56.第09章節(jié)-Python3.5-裝飾器之案例剖析2
  • 57.第10章節(jié)-Python3.5-裝飾器之終極講解
  • 58.第11章節(jié)-Python3.5-迭代器與生成器1
  • 59.第12章節(jié)-Python3.5-迭代器與生成器2
  • 60.第13章節(jié)-Python3.5-迭代器與生成器并行
    • Iterable isinstance
    • Iterator
    • iter()方法
  • 61.第14章節(jié)-Python3.5-內置方法詳解1-2
  • 63.第16章節(jié)-Python3.5-Json與pickle數據序列化
  • 64.第17章節(jié)-Python3.5-軟件目錄結構規(guī)范
  • 65.第18章節(jié)-w4-practices
  • 獲取文件所在路徑,添加到sys.path

50.第03章節(jié)-Python3.5-裝飾器詳解

1.裝修器定義:裝飾器本質是函數,(裝飾其它函數)就是為其它函數添加附件功能
2.原則:a)不能修改被裝飾函數的源代碼
b)不能修改被裝飾函數的調用方式

51.第04章節(jié)-Python3.5-裝飾器應用詳解

52.第05章節(jié)-Python3.5-裝飾器之函數即變量

53.第06章節(jié)-Python3.5-裝飾器之高階函數

高階函數:
a)把一個函數名當作實參傳給另一個函數(可以實現裝修器中的:不能修改被裝飾函數的源代碼的情況下為函數增加功能)

def bar():print("in the bar")def test(func):print(func)func()test(bar)

b)返回值中包含函數名(可以實現裝修器中的:不修改函數的調用方式)

import time def bar():time.sleep(3)print("in the bar")def test(func):print(func)return func# print(test(bar)) bar = test(bar) bar() #run bar

返回頂部

54.第07章節(jié)-Python3.5-裝飾器之嵌套函數

高階函數 + 嵌套函數 => 裝修器

x = 0 def gradpa():x = 1def dad():x = 2def son():x = 3print(x)son()dad() gradpa()

返回頂部

55.第08章節(jié)-Python3.5-裝飾器之案例剖析1

裝飾器一:

import time def timer(func):def deco():start_time = time.time()func()stop_time = time.time()print("the func run time is :{runtime}".format(runtime = (stop_time - start_time)))return deco@timer def test1():time.sleep(2)print("in the test1")test1()

返回頂部

56.第09章節(jié)-Python3.5-裝飾器之案例剖析2

裝飾器二:解決參數傳遞問題

import time def timer(func):def deco(*args,**kwargs):start_time = time.time()func(*args,**kwargs)stop_time = time.time()print("the func run time is :{runtime}".format(runtime = (stop_time - start_time)))return deco@timer def test1():time.sleep(2)print("in the test1")@timer def test2(name,age):time.sleep(2)print("in the test2:",name,age)test1() test2("alex",age = 32)

返回頂部

57.第10章節(jié)-Python3.5-裝飾器之終極講解

user = "wu" passwd = "pass"def auth(func):def wrapper(*args,**kwargs):username = input("please input username:")password = input("please input password:")if user == username and passwd == password:print("\033[32;1mUser has passed authentication\033[0m")res = func(*args,**kwargs)print("---after authentication---")return reselse:print("\033[31;1mInvalid username or password\033[0m")return wrapperdef index():print("welcome index page")@auth def home():print("welcome home page")def bbs():print("welcome bbs page")home()

ps:
1.理解參數傳遞過程
2.當層級較多時,可斷點調試

#!/usr/bin/env python # -*-coding:utf-8-*- # author: Mr.Wu user = "wu" passwd = "pass"def auth(auth_type):def outer_wrapper(func):def wrapper(*args, **kwargs):if auth_type == "local":username = input("please input username:")password = input("please input password:")if user == username and passwd == password:print("\033[32;1mUser has passed authentication\033[0m")res = func(*args, **kwargs)print("---after authentication---")return reselse:print("\033[31;1mInvalid username or password\033[0m")elif auth_type == "ldap":print("ldap authenticatoin")res = func(*args, **kwargs)print("---after authentication---")return resreturn wrapperreturn outer_wrapperdef index():print("welcome index page")@auth(auth_type="local") def home():print("welcome home page")return "from home"@auth(auth_type="ldap") def bbs():print("welcome bbs page")home() print(home()) bbs()

返回頂部

58.第11章節(jié)-Python3.5-迭代器與生成器1

生成器:只有在調用時才會生成相應的數據
生成器的優(yōu)點:可以節(jié)省內存資源
比較列表與生成器:

a = [ i*2 for i in range(10000000) ] b = ( i*2 for i in range(10000000) )

for n in b:
print(n)
b.next() #只有一個next方法,在python2中,為b.next()

#斐波拉契 # def fib(max): # a,b,n = 0,1,0 # while n < max: # a,b = b,a + b # print(a) # n = n + 1 # return "done" # # fib(10)#轉為生成器 def fib(max):a,b,n = 0,1,0while n < max:a,b = b,a + byield an = n + 1return "done"f = fib(10) print(f.__next__()) print("testxxx") print(f.__next__()) print(f.__next__()) print("testxxx") print(f.__next__())

返回頂部

59.第12章節(jié)-Python3.5-迭代器與生成器2

生成器案例:

import timedef consumer(name):print("{name}準備吃包子了".format(name = name))while True:baozi = yieldprint("包子{baozi}分給{name}吃了".format(baozi=baozi,name=name)) # c1 = consumer("user1") # c1.__next__() # c1.send("1") # c1.send("2")def producer(name):c1 = consumer("c1")c2 = consumer("c2")c1.__next__()c2.__next__()print("開始做包子了")baozi_no = 1for i in range(10):time.sleep(1)print("{name}做了2個包子".format(name=name))c1.send(baozi_no)c2.send(baozi_no+1)baozi_no = baozi_no + 2producer("alex")

返回頂部

60.第13章節(jié)-Python3.5-迭代器與生成器并行

Iterable isinstance

可以直接作用于for循環(huán)的對象統(tǒng)稱為可迭代對象:Iterable

from collections import Iterableprint(isinstance([],Iterable)) print(isinstance("",Iterable)) print(isinstance({},Iterable)) print(isinstance((),Iterable)) print(isinstance(100,Iterable))

Iterator

可以被next()函數調用并且不斷返回下一個值的對象稱為迭代器:Iterator
查看對像的方法:dir(對象)
使用

from collections import Iteratorprint(isinstance((x for x in range(5)), Iterator))

iter()方法

iter()方法可以把可迭代對象轉變?yōu)橐粋€迭代器對象
a = iter(['a','b','c'])
print(a.next())
print(a.next())

返回頂部

61.第14章節(jié)-Python3.5-內置方法詳解1-2

dir()
exec() #執(zhí)行一段代碼
eval() #將字典形式的字符串處理成字典類型
map()
globals() #獲取當前文件中所有全局變量,注:不包括函數中的局部變量
hash()
bin()
oct()
hex()
sorted()
把字典按key排序打印

a = {6:2,8:0,1:4,-5:6,99:11,4:32} print(a.items()) print(sorted(a.items())) print(sorted(a.items(),key=lambda x:x[1]))

zip()

a = ['a','b','c','d'] b = [1,2,3,4,5]for i in zip(a,b):print(i)

locals()

返回頂部

63.第16章節(jié)-Python3.5-Json與pickle數據序列化

json dumps/dump

import jsondata = {"key1":"value","key2":[1,2,3] }with open("json_1.txt","w") as f:f.write(json.dumps(data))#等價于import jsondata = {"key1":"value","key2":[1,2,3] }with open("json_1.txt","w") as f:json.dump(data,f)

json loads/load

import jsonwith open("json_1.txt", "r") as f:data = json.loads(f.read()) print(data) # 等價于 import jsonwith open("json_1.txt", "r") as f:data = json.load(f)print(data)

json編碼問題

import json dic = (1:'中國',2:'b') f = open('test_json.txt','w',encoding='utf-8') json.dump(dic, f, ensure_ascii=False) #json.dump(dic, f)#感受下如何不加ensure_ascii=False后,文件內容的區(qū)別 f.close() f = open('test_json.txt',encoding='utf-8') res = json.load(f) f.close() print(type(res), res)

pickle dumps/dump

import pickledef func_test(name):print(name)data = {"pickle":"dump","func":func_test }# with open("pickle_1.txt","wb")as f: # f.write(pickle.dumps(data)) #等價于with open("pickle_1.txt","wb")as f:pickle.dump(data,f)

pickle loads/load

import pickledef func_test(name):print("hello",name)# with open("pickle_1.txt","rb")as f: # print(pickle.loads(f.read())["func"]("test_name"))#等價于with open("pickle_1.txt","rb")as f:print(pickle.load(f)["func"]("test_name"))

返回頂部

64.第17章節(jié)-Python3.5-軟件目錄結構規(guī)范

注意:項目首字母大寫

Atm/ ├── bin │?? ├── atm.py │?? └── __init__.py ├── conf │?? └── __init__.py ├── core │?? ├── __init__.py │?? └── main.py ├── docs │?? ├── abc.rst │?? └── conf.py ├── logs │?? └── __init__.py ├── README ├── requirements.txt └── setup.py

目錄間程序調用
假如從bin下的atm調用core下的main
main.py

print("welcome to atm")

atm.py

import os, sysBASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) print(BASE_DIR) sys.path.append(BASE_DIR)from core import mainmain

返回頂部

65.第18章節(jié)-w4-practices

模擬實現一個ATM + 購物商城程序

額度 15000或自定義
實現購物商城,買東西加入 購物車,調用信用卡接口結賬
可以提現,手續(xù)費5%
每月22號出賬單,每月10號為還款日,過期未還,按欠款總額 萬分之5 每日計息
支持多賬戶登錄
支持賬戶間轉賬
記錄每月日常消費流水
提供還款接口
ATM記錄操作日志
提供管理接口,包括添加賬戶、用戶額度,凍結賬戶等。。。
用戶認證用裝飾器
示例代碼 https://github.com/triaquae/py3_training/tree/master/atm

獲取文件所在路徑,添加到sys.path

from os import getcwd,path from sys import path as sys_path sys_path.insert(0,path.dirname(getcwd()))

python_控制臺輸出帶顏色的文字方法:
https://www.cnblogs.com/Eva-J/p/8330517.html

?

轉載于:https://www.cnblogs.com/rootid/p/9388396.html

總結

以上是生活随笔為你收集整理的W4_python_decorator_generator_Iteratable_Iterator_json_pickle的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。