writing idiomatic python 读书笔记(2)

函数和异常的使用实例
Function
(1)避免使用一个可变对象作为函数参数的默认值
   
   
def f(a,L=[])
L.append(a)
return L
print(f(1)) #[1]
print(f(2)) #[1,2]
print(f(3)) #[1,2,3]
得出了意想不到的结果。。。如果碰到这样的情况,估计得想破脑袋,乍看逻辑和代码都没问题
需要这么写:
   
   
def f(a,L=None)
if L is None:
L= []
L.append(a)
return L
(2)使用判断表达式来代替返回值:
harmful:
   
   
def all_equal(a,b,c):
result = False
if a==b==c:
result = True
return result

idiomatic:
   
   
def all_equal(a,b,c):
return a==b==c

(3)正确使用关键字参数
这个比较好理解也正常不会有问题,贴个例子:
Harmful:
    
    
def print_list(list_value, sep):
    print('{}'.format(sep).join(list_value))
the_list = ['a', 'b', 'c']
the_other_list = ['Jeff', 'hates', 'Java']
print_list(the_list, ' ')
print_list(the_other_list, ' ')
print_list(the_other_list, ', ')

Idiomatic:
    
    
def print_list(list_value, sep=' '):
    print('{}'.format(sep).join(list_value))
the_list = ['a', 'b', 'c']
the_other_list = ['Jeff', 'hates', 'Java']
print_list(the_list)
print_list(the_other_list)
print_list(the_other_list, ', ')

(4)使用* args,* * kwargs接受任意参数
   
   
def make_api_call(foo, bar, baz, *args, **kwargs):

(5)学会将函数作为值
   
   
import operator as op
for operator in (op.add, op.sub, op.mul, op.div):
    print_table(operator)
(6)使用基于函数的版本的打印 
   
   
Harmful:
print 1, 'foo', __name__
 Idiomatic:
from __future__ import print_function       #为了向3.x过度吧
print(1, 'foo', __name__)
Exceptions
(1)不要怕使用异常
(2)使用异常来写代码
   
   
def get_log_level(config_dict):
try:
if config_dict['ENABLE_LOGGING']:
return config_dict['DEFAULT_LOG_LEVEL']
except KeyError:
# if either value wasn't present, a
# KeyError will be raised, so
# return None
return None
(3)不必要抓住所有异常
   
   
import requests
def get_json_response(url):
return requests.get(url).json()
# If we need to make note of the exception, we
# would write the function this way...
def alternate_get_json_response(url):
try:
r = requests.get(url)
return r.json()
except:
# do some logging here, but don't handle the exception
# ...
raise




  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值