python小知識點
傳遞元組
一個函數(shù)中返回兩個不同的值
-
案例:
>>> def get_error_details(): return (2,"details"); >>> >>> errnum,errstr = get_error_details(); >>> errnum 2 >>> errstr 'details' >>>
-
注意
-
a,b=<some expression>的用法會將表達式的結(jié)果解釋為具有兩個值的一個元組。這也意味著在Python中交換兩個變量的最快方法是:
>>> a=5;b=9; >>> a,b (5, 9) >>> a,b=b >>> a,b=b,a >>> a,b (9, 5) >>>
-
特殊方法
- 諸如init和del等一些方法對于類來說有特殊意義瑞佩;特殊方法用來模擬內(nèi)置類的某些行為
- 如果你想了解所有的特殊方法来吩,請參閱手冊
單語句塊
-
案例:
>>> flag = True; >>> if flag:print('Yes'); Yes >>>
單個語句是原地立即使用的,它不會被看作是一個單獨的塊。
Lambda表格
lambda語句可以創(chuàng)建一個新的函數(shù)對象迅办。從本質(zhì)上說蛔添,lambda需要一個參數(shù),后跟一個表達式作為函數(shù)體姻报,這一表達式執(zhí)行的值將作為這個新函數(shù)的返回值
-
案例:
points = [{'x':2,'y':3}, {'x':4,'y':1}]; points.sort(key=lambda i: i['y']); print(points); C:\Users\Administrator\Desktop>python hello.py [{'x': 4, 'y': 1}, {'x': 2, 'y': 3}]
- 要注意到一個list的sort方法可以獲得一個key參數(shù)己英,用以決定列表的排序方式。在我們的案例中吴旋,我們希望進行一次自定義排序损肛,為此我們需要編寫一個函數(shù)厢破,但是又不是為函數(shù)編寫一個獨立的def塊,只在這一個地方使用治拿,因此我們使用Lambda表達式來創(chuàng)建一個新函數(shù)
列表推導
列表推導(List Comprehension)用于從一份現(xiàn)有的列表中得到一份新列表
-
案例:
listone=[2,3,4]; listtwo=[2*i for i in listone if i>2]; print(listtwo); C:\Users\Administrator\Desktop>python hello.py [6, 8]
當滿足了某些條件時(if i>2),我們進行指定的操作(2*i)摩泪,以此來獲得一份新的列表。要注意到原始列表依舊保持不變
在函數(shù)中接受元組與字典
有一種特殊方法忍啤,即分別用*或**作為元組或字典的前綴加勤,來使它們作為一個參數(shù)為函數(shù)所接收。當函數(shù)需要一個可變數(shù)量的實參時同波,這將頗為有用
-
案例:
>>> def powersum(power,*argv): total = 0; for i in argv: total += pow(i,power); return total; >>> powersum(2,3,4) 25
- 因為我們在args變量前添加了一個*前綴鳄梅,函數(shù)的所有額外參數(shù)都將傳遞到argv中,并作為一個元組予以存儲
assert語句
assert語句用以斷言某事是真的未檩。如果其不是真的戴尸,就拋出一個錯誤
-
案例:
>>> mylist=['ab','ff']; >>> assert len(mylist)>=2; >>> mylist.pop(); 'ff' >>> assert len(mylist)>=2 Traceback (most recent call last): File "<pyshell#30>", line 1, in <module> assert len(mylist)>=2 AssertionError >>>
裝飾器
裝飾器(Decorators)是應用包裝函數(shù)的快捷方式。這有助于將某一功能與一些代碼一遍又一遍地“包裝”
舉個例子冤狡,我為自己創(chuàng)建了一個retry裝飾器孙蒙,這樣我可以將其運用到任何函數(shù)之中,如果在一次運行中拋出了任何錯誤悲雳,它就會嘗試重新運行挎峦,直到最大次數(shù)5次,并且每次運行期間都會有一定的延遲合瓢。這對于你在對一臺遠程計算機執(zhí)行網(wǎng)絡調(diào)用的情況十分有用:
-
案例:
from time import sleep from functools import wraps import logging logging.basicConfig() log = logging.getLogger("retry") def retry(f): @wraps(f) def wrapped_f(*args,**kwargs): MAX_ATTEMPTS = 5; for attempt in range(1,MAX_ATTEMPTS+1): try: return f(*args,**kwargs); except: log.exception("Attempt %s/%s failed: %s", attempt,MAX_ATTEMPTS, (args,kwargs)); sleep(10*attempt); log.critical("All %s attempts failed : %s", MAX_ATTEMPTS,(args,kwargs)); return wrapped_f; counter = 0; @retry def save_to_database(arg): 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; #這將在第一次調(diào)用時拋出異常 #在第二次運行時將正常工作 if counter<2: raise ValueError(arg); if __name__=="__main__": save_to_database("Some bad value"); C:\Users\Administrator\Desktop>python hello.py powersum(2,3,4) Write to a database or make a network call or etc. This will be automatically retried if exception is thrown ERROR:retry:Attempt 1/5 failed: (('Some bad value',), {}) Traceback (most recent call last): File "hello.py", line 12, in wrapped_f return f(*args,**kwargs); File "hello.py", line 31, in save_to_database raise ValueError(arg); ValueError: Some bad value Write to a database or make a network call or etc. This will be automatically retried if exception is thrown