Python--良好的代码风格

清晰明了

Bad

def make_complex(*args):
    x, y = args
    return dict(**locals())
Good

def make_complex(x, y):
    return {'x': x, 'y': y}


一行一语句

Bad

print 'one'; print 'two'

if x == 1: print 'one'

if <complex comparison> and <other complex comparison>:
    # do something
Good

print 'one'
print 'two'

if x == 1:
    print 'one'

cond1 = <complex comparison>
cond2 = <other complex comparison>
if cond1 and cond2:
    # do something

 

函数参数

1、位置参数

send(message, recipient) or point(x, y) 符合常理
send(recipient='World', message='Hello') and point(y=2, x=1) 容易误解 

2、关键参数

send(message, to, cc=None, bcc=None). 
send('Hello', 'World', 'Cthulhu', 'God'), 不好
send('Hello again', 'World', bcc='God', cc='Cthulhu'). 乱序,也不好
send('Hello', 'World', cc='Cthulhu', bcc='God').按顺序,指定,最好


3、任意参数列表

send(message, *args) 
 send('Hello', 'God', 'Mom', 'Cthulhu')     # args=['God', 'Mom', 'Cthulhu']
这样更好些

send(message, recipients) 
send('Hello', ['God', 'Mom', 'Cthulhu']).

4、任意参数字典
send(message, **kargs) 
同上

参数良好原则:
a、易读:参数不用注释别人都明白
b、易改:修改参数不会影响其他参数


函数返回
def complex_function(a, b, c):
    if not a:
        return None  # Raising an exception might be better
    if not b:
        return None  # Raising an exception might be better
    # Some complex code trying to compute x from a, b and c
    # Resist temptation to return x if succeeded
    if not x:
        # Some Plan-B computation of x
    return x  # One single exit point for the returned value x will help
              # when maintaining the code.

真值检验

Bad:

if attr == True:
    print 'True!'

if attr == None:
    print 'attr is None!'
Good:

# Just check the value
if attr:
    print 'attr is truthy!'

# or check for the opposite
if not attr:
    print 'attr is falsey!'

# or, since None is considered false, explicitly check for it
if attr is None:
    print 'attr is None!'


获取字典元素
Bad:
d = {'hello': 'world'}
if d.has_key('hello'):
    print d['hello']    # prints 'world'
else:
    print 'default_value'
Good:
d = {'hello': 'world'}
print d.get('hello', 'default_value') # prints 'world'
print d.get('thingy', 'default_value') # prints 'default_value'

# Or:
if 'hello' in d:
    print d['hello']

#《doc》
get(key[, default])
Return the value for key if key is in the dictionary, else default. If default is not given, it defaults to None, so that this method never raises a KeyError.

has_key(key)
Test for the presence of key in the dictionary. has_key() is deprecated in favor of key in d.

列表捷径

Bad:

# Filter elements greater than 4
a = [3, 4, 5]
b = []
for i in a:
    if i > 4:
        b.append(i)
Good:

a = [3, 4, 5]
b = [i for i in a if i > 4]
b = filter(lambda x: x > 4, a)
Bad:

# Add three to all list members.
a = [3, 4, 5]
for i in range(len(a)):
    a[i] += 3
Good:

a = [3, 4, 5]
a = [i + 3 for i in a]
# Or:
a = map(lambda i: i + 3, a)



文件操作

Bad:

f = open('file.txt')
a = f.read()
print a
f.close()
Good:

with open('file.txt') as f:
    for line in f:
        print line

用with更好,它会自动关闭文件,甚至是有异常时也会这样。


特长的行

Bad:

my_very_big_string = """For a long time I used to go to bed early. Sometimes, \
    when I had put out my candle, my eyes would close so quickly that I had not even \
    time to say “I’m going to sleep.”"""

from some.deep.module.inside.a.module import a_nice_function, another_nice_function, \
    yet_another_nice_function
很多人习惯用反斜杠续行,但要是不小心在反斜杠后面加了个空格,你发现不了,但会出错。
用一对圆括号就很好,解释器就一直找到右括号为止作为一个逻辑行。
Good:

my_very_big_string = (
    "For a long time I used to go to bed early. Sometimes, "
    "when I had put out my candle, my eyes would close so quickly "
    "that I had not even time to say “I’m going to sleep.”"
)

from some.deep.module.inside.a.module import (
    a_nice_function, another_nice_function, yet_another_nice_function)












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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值