more_return_values.py
# 讓一個(gè)函數(shù)返回兩個(gè)或多個(gè)不同的值
def get_morevalues():
shoplist = ['apple','mango','carrot']
str = 'This is the second value'
a = 3
# 通過(guò)一個(gè)元組就可以返回多個(gè)值
return(shoplist,str,a)
# Unpackage 要注意數(shù)量要對(duì)應(yīng)
first_value,second_value,third_value = get_morevalues()
print(first_value)
print(second_value)
print(third_value)
more_swaptip.py
# Python中交換兩個(gè)變量的方法
# a,b = some expression 會(huì)把表達(dá)式的結(jié)果解釋為具有兩個(gè)值的一個(gè)元組
a = 5
b = 8
print('a = {}, b = {}'.format(a,b))
a,b = b,a
print('a = {}, b = {}'.format(a,b))
more_single_sentenceblock.py
# 單個(gè)語(yǔ)句塊
# 如果語(yǔ)句塊只包括單獨(dú)的一句語(yǔ)句 那么你可以在同一行指定它
# 當(dāng)然這種方法不建議使用
flag = True
if flag: print('Yes')
more_lambda.py
# lambda語(yǔ)句
# 它可以創(chuàng)建一個(gè)新的函數(shù)對(duì)象
# 需要一個(gè)參數(shù),后跟一個(gè)表達(dá)式做為函數(shù)體瓶蚂,表達(dá)式的值作為函數(shù)的返回值
points = [{'x': 2, 'y': 3}, {'x': 4, 'y': 1}]
# 還不是很懂這句話
points.sort(key=lambda i:i['y'])
print(points)
more_list_comprehension.py
# 用現(xiàn)有的列表中得到一份新列表
listone = [2,3,4]
listtwo = [2*i for i in listone if i > 2]
print(listone) # listone不變
print(listtwo)
more_receive_tuple_and_dict.py
# 在函數(shù)中接受元組與字典
# 用 * 作為元組前綴
# 用 ** 作為字典前綴
def powersum(power, *args):
'''Return the sum of each argument raised to the specified power.'''
total = 0
for i in args:
total += pow(i,power)
return total
print(powersum(2,3,4,5))
print(powersum(2,10))
more_assert.py
# Assert語(yǔ)句
# assert用來(lái)斷言某事是真
# ex:你非常確定你正在使用的列表中至少包含一個(gè)元素扼雏,想確認(rèn)這一點(diǎn),
# 如果其不是真的就跑出一個(gè)錯(cuò)誤
mylist = ['item']
assert len(mylist) >= 1
print(mylist.pop())
assert len(mylist) >= 1
more_decorates.py
# 關(guān)于裝飾器一點(diǎn)都看不懂 到時(shí)候看Cookbook吧
# 裝飾器Decorators 能夠包裝函數(shù)
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("Attemp %s%s failed : %s",attempt,MAX_ATTEMPTS,(args,kwargs))
sleep(10 * attempt)
log.critial("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 retired if exception is thrown.')
global counter
count += 1
if counter >= 2:
raise ValueError(arg)
if __name__ == '__main__':
save_to_database('Some bad value')