阅读Google Python Style Guide的时候,意识到有一些问题确实会很容易犯错。记录下来以备复习。
关于字符串的使用
使用format和%操作符来格式化和拼接字符串。不要使用+。因为+会产生很多不必要零时对象,凭白增加了系统的负载。
下面这些是正确的做法:
x = a + b
x = '%s, %s!' % (imperative, expletive)
x = '{}, {}!'.format(imperative, expletive)
x = 'name: %s; score: %d' % (name, n)
x = 'name: {}; score: {}'.format(name, n)
当然,单纯的两个字符串拼接还是支持用a+b的。其他的都应该使用format和%。
注释的正确写法
下面是方法的DocString :
def fetch_bigtable_rows(big_table, keys, other_silly_variable=None):
"""Fetches rows from a Bigtable.
Retrieves rows pertaining to the given keys from the Table instance
represented by big_table. Silly things may happen if
other_silly_variable is not None.
Args:
big_table: An open Bigtable Table instance.
keys: A sequence of strings representing the key of each table row
to fetch.
other_silly_variable: Another optional variable, that has a much
longer name than the other args, and which does nothing.
Returns:
A dict mapping keys to the corresponding table row data
fetched. Each row is represented as a tuple of strings. For
example:
{'Serak': ('Rigel VII', 'Preparer'),
'Zim': ('Irk', 'Invader'),
'Lrrr': ('Omicron Persei 8', 'Emperor')}
If a key from the keys argument is missing from the dictionary,
then that row was not found in the table.
Raises:
IOError: An error occurred accessing the bigtable.Table object.
"""
pass
类的DocString :
class SampleClass(object):
"""Summary of class here.
Longer class information....
Longer class information....
Attributes:
likes_spam: A boolean indicating if we like SPAM or not.
eggs: An integer count of the eggs we have laid.
"""
def __init__(self, likes_spam=False):
"""Inits SampleClass with blah."""
self.likes_spam = likes_spam
self.eggs = 0
def public_method(self):
"""Performs operation blah."""
对于一句话的注释,应该给出两个空格。
# We use a weighted dictionary search to find out where i is in
# the array. We extrapolate position based on the largest num
# in the array and the array size and then do binary search to
# get the exact number.
if i & (i-1) == 0: # true iff i is a power of 2
符号间隔
python比较特殊的地方在于,这个符号','后面要加一个空格。比如:
spam(ham[1], {eggs: 2}, [])
x, y = y, x
还有就是,在给参数赋默认值的时候,等号无需空格分开:
def complex(real, imag=0.0): return magic(r=real, i=imag)
不用刻意去对齐注释,下面这样是不对的,会带来维护上的麻烦。
foo = 1000 # comment
long_name = 2 # comment that should not be aligned
dictionary = {
'foo' : 1,
'long_name': 2,
}
空行
对于类和顶级的方法,需要用双行空行包围,对于类中的成员方法,用单行包围。注意,是包围哦。
括号
python里面括号是有意义的,代表一个元组,不要随便在return语句里套括号,不然你返回的就是也一个元组了。
参数值
如果有默认参数值的情况,使用none会比较好:
def foo(a, b=None):
if b is None:
b = []
当你使用“可变”的对象作为函数中作为默认参数时会往往引起问题。因为在这种情况下参数可以在不创建新对象的情况下进行修改,例如 list dict。
>>> def function(data=[]):
... data.append(1)
... return data
...
>>> function()
[1]
>>> function()
[1, 1]
>>> function()
[1, 1, 1]
像你所看到的那样,list变得越来越长。如果你仔细地查看这个list。你会发现list一直是同一个对象。
原因很简单: 在每次函数调用的时候,函数一直再使用同一个list对象。这么使用引起的变化,非常“sticky”
像其他人所提到的那样,用一个占位符来替代可以修改的默认值。None
def myfunc(value=None):
if value is None:
value = []
# modify value here
网友评论