More Information

more_return_values.py

# 让一个函数返回两个或多个不同的值

def get_morevalues():
    shoplist = ['apple','mango','carrot']
    str = 'This is the second value'
    a = 3
    # 通过一个元组就可以返回多个值
    return(shoplist,str,a)

# Unpackage 要注意数量要对应

first_value,second_value,third_value = get_morevalues()

print(first_value)
print(second_value)
print(third_value)

more_swaptip.py

# Python中交换两个变量的方法
# a,b = some expression 会把表达式的结果解释为具有两个值的一个元组
a = 5
b = 8
print('a = {}, b = {}'.format(a,b))
a,b = b,a
print('a = {}, b = {}'.format(a,b))

more_single_sentenceblock.py

# 单个语句块
# 如果语句块只包括单独的一句语句 那么你可以在同一行指定它
# 当然这种方法不建议使用
flag = True
if flag: print('Yes')

more_lambda.py

# lambda语句
# 它可以创建一个新的函数对象 
# 需要一个参数,后跟一个表达式做为函数体,表达式的值作为函数的返回值

points = [{'x': 2, 'y': 3}, {'x': 4, 'y': 1}]

# 还不是很懂这句话
points.sort(key=lambda i:i['y'])

print(points)

more_list_comprehension.py

# 用现有的列表中得到一份新列表

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

# 在函数中接受元组与字典
# 用 * 作为元组前缀
# 用 ** 作为字典前缀

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语句
# assert用来断言某事是真
# ex:你非常确定你正在使用的列表中至少包含一个元素,想确认这一点,
# 如果其不是真的就跑出一个错误

mylist = ['item']
assert len(mylist) >= 1
print(mylist.pop())

assert len(mylist) >= 1

more_decorates.py

# 关于装饰器一点都看不懂 到时候看Cookbook吧
# 装饰器Decorators 能够包装函数
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')

你可能感兴趣的:(More Information)