傳遞元組
如下
# 傳遞元組
def get_error_details():
return (2,'details')
errnum,errstr = get_error_details()
print(errnum)
print(errstr)
# 快速交換兩個變量
errstr,errnum = errnum,errstr
print(errnum)
print(errstr)
控制臺
2
details
details
2
Process finished with exit code 0
a,b = <some expression>
將表達(dá)式解釋為具有兩個值的一個元組堤结。
快速交換兩個變量的方法如上。
特殊方法
更所的特殊方法鸭丛,請參考這里
# 特殊方法 舉例說明
# __init__(self,...) 這一方法在新創(chuàng)建的對象被返回準(zhǔn)備調(diào)用時被調(diào)用
# __del__(self) 這一方法在對象被刪除之前調(diào)用(但是它的使用實際不可預(yù)測竞穷,所以避免使用)
# __str__(self) 當(dāng)我們使用print函數(shù)時,或者str()被使用時就會被調(diào)用
# __it__(self,other) 當(dāng)小于運算符(<)被使用時被調(diào)用鳞溉。類似瘾带,使用其它所有運算符時都會有特殊方法被調(diào)用
# __getitem__(self,key) 使用x[key]索引操作時被調(diào)用
# __len__(self) 當(dāng)針對序列對象使用內(nèi)置len()函數(shù)時被調(diào)用
單語句塊
我們已經(jīng)見過每一個語句塊都由其自身的縮進(jìn)級別與其它部分相區(qū)分。但是如果語句塊只包括單獨的一行語句熟菲,那么我們可以在同一行指定它看政,比如條件語句和循環(huán)語句。
如下
flag = True
if flag: print('YES')
單個語句是在原地立即使用的抄罕,它不會被看做一個單獨的塊允蚣。
Lambda表格
lambda語句可以創(chuàng)建一個新的函數(shù)對象。從本質(zhì)上說呆贿,lambda需要一個參數(shù)厉萝,后跟一個表達(dá)式作為函數(shù)體,這個表達(dá)式執(zhí)行的值將作為這個新函數(shù)的返回值榨崩。
如下
# lambda表達(dá)式
point = [
{'x':2,'y':3},
{'x':4,'y':7}
]
point.sort(key=lambda i:i['x'])
print(point)
print("****************")
z = lambda x,y,z:x*y*z
print(z(999,95,82))
控制臺輸出
[{'x': 2, 'y': 3}, {'x': 4, 'y': 7}]
****************
77892210
Process finished with exit code 0
當(dāng)我們需要編寫一個函數(shù)谴垫,又不想為函數(shù)編寫一個獨立的def
塊時,就可以使用lambda
表達(dá)式母蛛。
列表推導(dǎo)
列表推導(dǎo)用于從現(xiàn)有的列表中得到一份新的列表翩剪。當(dāng)我們循環(huán)處理列表中的元素,并將其存儲在一個新的列中中時彩郊,列表推導(dǎo)可以省下很多代碼前弯。
如下
# 列表推導(dǎo)
# 從已有列表中國推導(dǎo)出一份新的列表
listone = [2,3,4,5,6]
listtwo = [2*i*i for i in listone if i>3]
print(listtwo)
控制臺
[32, 50, 72]
Process finished with exit code 0
在函數(shù)中接收元組與字典
如下
# 在函數(shù)中接收元組與字典
# 接收元組
def powerSum(poewr,*ele):
total = 0
for i in ele:
print(i)
total += pow(i,poewr)
return total
# 接收字典
def getkeyvalue(p,**dic):
for k in dic.values():
print(k*p)
print(dic)
print(getkeyvalue(3,a=3,b=4))
print('=====================')
print(powerSum(10,5,9,11))
控制臺
9
12
{'a': 3, 'b': 4}
None
=====================
5
9
11
29433974627
Process finished with exit code 0
如上,我們使用*
作為元組的前綴秫逝,函數(shù)所有的其它額外參數(shù)都將傳遞到ele
中恕出,并作為一個元組進(jìn)行存儲。**
作為字典的前綴违帆,額外的參數(shù)將被視為字典的鍵值對進(jìn)行存儲浙巫,并且,在傳遞參數(shù)時必須采用key=value
的形式。
assert
語句
assert
用來斷言Assert
某件事是真的的畴,如果不是真的渊抄,就會拋出AssertionError
錯誤。
如下
# assert 語句
text = input('Please input content:')
assert len(text) > 5
控制臺
Please input content:qwert
Traceback (most recent call last):
File "/Users/a1/Desktop/Python/PythonProjectFiles/More.py", line 62, in <module>
assert len(text) > 5
AssertionError
Process finished with exit code 1
如上丧裁,我們斷言輸入字符串的長度會大于5护桦,當(dāng)我們輸入字符串長度小于等于5時,就會拋出AssertionError
煎娇。
相比捕獲異常 以及定位問題或向用戶顯示錯誤信息然后退出二庵,斷言的優(yōu)勢更為明顯。
裝飾器
裝飾器是應(yīng)用包裝函數(shù)的快捷方式缓呛,這有助于將某一功能與一些代碼一遍又一遍的“包裝”眨猎。如下,創(chuàng)建一個retry
裝飾器
from time import sleep
from functools import wraps
import logging
logging.basicConfig()
log = logging.getLogger('retry')
def retry(f):
@wraps(f)
def wrapped_f(*tup,**dic):
MAX_ATTEMPTS = 5
for attempt in range(1,MAX_ATTEMPTS + 1):
try:
return f(*tup,**dic)
except:
log.exception("Attemp %s%s failed:%s",
attempt,
MAX_ATTEMPTS,
(tup,dic))
sleep(2 * attempt)
log.critical("All %s attemp failed: %s",
MAX_ATTEMPTS,
(tup,dic))
return wrapped_f
counter = 0
@retry
def saveToDatabase(ele):
print("Write to a database or make a network call or etc.")
print("This will be automatically retried if exception is thrown.")
global counter
counter += 1
# 前3次調(diào)用時拋出異常
# 第四次運行時講正常工作(重試)
if counter < 4:
raise ValueError(ele)
if not __name__ == 'main':
saveToDatabase('Some bad value')
控制臺
ERROR:retry:Attemp 15 failed:(('Some bad value',), {})
Traceback (most recent call last):
File "/Users/a1/Desktop/Python/PythonProjectFiles/Decorators.py", line 14, in wrapped_f
return f(*tup,**dic)
File "/Users/a1/Desktop/Python/PythonProjectFiles/Decorators.py", line 37, in saveToDatabase
raise ValueError(ele)
ValueError: Some bad value
Write to a database or make a network call or etc.
This will be automatically retried if exception is thrown.
ERROR:retry:Attemp 25 failed:(('Some bad value',), {})
Write to a database or make a network call or etc.
Traceback (most recent call last):
This will be automatically retried if exception is thrown.
File "/Users/a1/Desktop/Python/PythonProjectFiles/Decorators.py", line 14, in wrapped_f
return f(*tup,**dic)
File "/Users/a1/Desktop/Python/PythonProjectFiles/Decorators.py", line 37, in saveToDatabase
raise ValueError(ele)
ValueError: Some bad value
ERROR:retry:Attemp 35 failed:(('Some bad value',), {})
Write to a database or make a network call or etc.
Traceback (most recent call last):
This will be automatically retried if exception is thrown.
File "/Users/a1/Desktop/Python/PythonProjectFiles/Decorators.py", line 14, in wrapped_f
return f(*tup,**dic)
File "/Users/a1/Desktop/Python/PythonProjectFiles/Decorators.py", line 37, in saveToDatabase
raise ValueError(ele)
ValueError: Some bad value
Write to a database or make a network call or etc.
This will be automatically retried if exception is thrown.
Process finished with exit code 0
如上 retry
裝飾器强经,可以將它運行到任何函數(shù)中,如果在前三次運行中拋出任何錯誤寺渗,它將會嘗試重新運行匿情,直到最大運行次數(shù)5次,并且每次重新運行之間還會有一定時間的延遲信殊。
關(guān)于裝飾器炬称,可以參考 one 和two