传递元祖
- 从一个函数中返回两个不同的值。
代码示例
>>> def detail():
... return (2,'details')
...
>>> errnum,errstr = detail()
>>> errnum
2
>>> errstr
'details'
注意a,b = <>
这种用法会将表达式解释为具有两个值的元组。
- 交换两个变量
代码实现
>>> a=3;b=4
>>> a,b
(3, 4)
>>> a,b = b,a
>>> a,b
(4, 3)
特殊方法
-
__init__(self,…)
新创建对象被返回准备使用时调用 -
__def__(self)
在对象呗删除之前调用,最好避免使用它 -
__str__(self)
使用print
函数或str()
被调用 -
__lt__(self,other)
当小于运算符(<)
使用时被调用.其他运算符也有相对应的特殊方法 -
__getitem__(self,key)
使用arr[key]
索引操作会被调用 -
__len__(self)
当序列对象使用内置len()
函数时被调用
单句语块
代码示例:
>>> flag = True
>>> if flag: print('True')
...
True
当语句块只包含一句语句时,可以在同行指定,比如条件语句和循环语句.
不建议采用上述方式
Lambda 表格
Lamdba
语句可以创建一个新的函数对象.lambda
只需要一个参数,后面跟一个表达式作为函数体,该表达式执行的值将作为新函数的返回值.
示例代码:
points = [{'a':10,'b':11},
{'a':9,'b':1}]
points.sort(key=lambda i:i['b'])
print(points)
输出结果:
[{'a': 9, 'b': 1}, {'a': 10, 'b': 11}]
list 的sort
方法可以获取一个"key"参数,用以决定列表排序方式(默认升序).上述方法是根据b
自定义排序.
列表推导
列表推导(List Comprehension)从现有的列表中得到一份新的列表.
代码示例
list = [1,2,3,4]
listTwo = [i*2 for i in list if i>2]
print(listTwo)
list 中满足i>2
,进行操作i*2
,获取一份新的列表,原列表保持不变.使用列表推导优点是,当使用循环来处理列表中元素并将其储存在新的列表中,减少代码的数量,方便快捷.
函数接收元组与字典
使用*
作为元组
的前缀,使用**
作为字典
的前缀,作为一个参数被函数接收.尤其在函数需要一个可变数量的参数时,尤为有用.
代码示例
# 数组平方求和
def powerSum(power,*arr):
total = 0
for i in arr:
total += pow(i,power)
return total
print(powerSum(2,4,5))
# 计算 4^2+5^2
print(powerSum(2,10))
# 计算 10^2
输出结果:
41
100
我们再函数参数使用*
标记arr
变量.调用时除第一位置的参数余下的参数将全部传入arr
中.如果使用**
余下参数将被视为字典.
assert 语句
assert
语句用于判断某操作是否为真.如果非真,就抛出一个错误,失败时会抛出AssertionError
.
代码示例
>>> print(list)
[1, 2, 3, 4]
>>> assert len(list)>3
>>> assert len(list)>5
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AssertionError
某些情况下Assert
好过异常捕获,也好过定位问题或像用户展示错误信息后退出.灵活使用该语句.
装饰器
装饰器(Decorators)是应用包装函数的快捷方式.有助于把某一功能与某些代码重复"包装".远程计算机进行网络调用的情况十分有用.
示例代码:
from time import sleep
from functools import wraps
import logging
logging.basicConfig()
log = logging.getLogger("retry")
def retry(f):
@wraps(f)
def wrap_f(*arr,**dict):
Max_Attempts = 5
for item in range(1,Max_Attempts+1):
try:
return f(*arr,**dict)
except:
log.exception("Attempt %s%s failed:%s",item,Max_Attempts,(arr,dict))
log.critical("All %s attempts faild :%s",Max_Attempts,(arr,dict))
return wrap_f()
couter = 0
@retry
def save_database(arr):
print('=====automactically=====')
global couter
couter = couter+1
# 第一次调用时候抛出异常,第二次运行时正常工作
if couter < 2:
raise ValueError(arr)
if __name__ == '__main__':
save_database('Some bad value')
输出结果:
ERROR:retry:Attempt 15 failed:((), {})
Traceback (most recent call last):
File "/Users/let/python3/20171213/pyStandradLib.py", line 63, in wrap_f
return f(*arr,**dict)
TypeError: save_database() missing 1 required positional argument: 'arr'
CRITICAL:retry:All 5 attempts faild :((), {})
ERROR:retry:Attempt 25 failed:((), {})
Traceback (most recent call last):
File "/Users/let/python3/20171213/pyStandradLib.py", line 63, in wrap_f
return f(*arr,**dict)
TypeError: save_database() missing 1 required positional argument: 'arr'
CRITICAL:retry:All 5 attempts faild :((), {})
ERROR:retry:Attempt 35 failed:((), {})
Traceback (most recent call last):
File "/Users/let/python3/20171213/pyStandradLib.py", line 63, in wrap_f
return f(*arr,**dict)
TypeError: save_database() missing 1 required positional argument: 'arr'
CRITICAL:retry:All 5 attempts faild :((), {})
ERROR:retry:Attempt 45 failed:((), {})
Traceback (most recent call last):
File "/Users/let/python3/20171213/pyStandradLib.py", line 63, in wrap_f
return f(*arr,**dict)
TypeError: save_database() missing 1 required positional argument: 'arr'
CRITICAL:retry:All 5 attempts faild :((), {})
ERROR:retry:Attempt 55 failed:((), {})
Traceback (most recent call last):
File "/Users/let/python3/20171213/pyStandradLib.py", line 63, in wrap_f
return f(*arr,**dict)
TypeError: save_database() missing 1 required positional argument: 'arr'
CRITICAL:retry:All 5 attempts faild :((), {})
Traceback (most recent call last):
File "/Users/let/python3/20171213/pyStandradLib.py", line 82, in <module>
save_database('Some bad value')
TypeError: 'NoneType' object is not callable
原理参考:
https://www.ibm.com/developerworks/linux/library/l-cpdecor/index.html
http://y.tsutsumi.io/dry-principles-through-python-decorators.html
网友评论