python之coding style
定义private
外部不需要的对象全部定义为private,只有外部需要引用函数才定义成public(往往将有主要功能的对象全都定义为private,然后定义一个public指向它,提供接口)
分隔长行
折叠长行的首选方法是使用Pyhon支持的圆括号,方括号(brackets)和花括号(braces)内的行延续.
如果需要,你可以在表达式周围增加一对额外的圆括号, 但是有时使用反斜杠看起来更好.确认恰当得缩进了延续的行
#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)
空行:
用两行空行分割顶层函数和类的定义。类内方法的定义用单个空行分割. 在'class'行和第一个方法定义之间也要有一个空行.
空格
spam( ham[ 1 ], { eggs: 2 } ) 改成 spam(ham[1], {eggs: 2})
始终在运算符两边放置一个空格
不要在用于指定关键字参数或默认参数值的'='号周围使用空格. def hello(string='hello')
字符串处理
如果是创建一个新字符串,用+不错.但如果是修改已有字符串,则用join()更有效率. 而且用 list comprehensions 比 append() 更有效率.
foo = 'foo' bar = 'bar' foobar = foo + bar # This is good foo += 'ooo' # This is bad, instead you should do: foo = ''.join([foo, 'ooo']) # Bad nums = "" for n in range(20): nums += str(n) # slow and inefficient print nums # Good nums = [] for n in range(20): nums.append(str(n)) print "".join(nums) # much more efficient # Best nums = [str(n) for n in range(20)] print "".join(nums)
+, join()也可用%s, format()取代(建议format())
foo = 'foo' bar = 'bar' foobar = '%s%s' % (foo, bar) # It is OK foobar = '{0}{1}'.format(foo, bar) # It is better foobar = '{foo}{bar}'.format(foo=foo, bar=bar) # It is best
列表
# Bad a = [3, 4, 5] b = [] for i in a: if i > 4: b.append() # Good a = [3, 4, 5] b = [i for i in a if i > 4] # or b = filter(lambda x: x > 4, a)
字典
# 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']
函数
函数尽量保持一个出口(方便debug)
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 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 if attr: print 'attr is truthy!'
2015-05-15