Python风格规范
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Python风格规范相关的知识,希望对你有一定的参考价值。
Python风格规范
分号
行长度
- 每行长度不超过80个字符;
-
# True x = (‘This will build a very long long ‘ ‘long long long long long long string‘)
括号
缩进
空行
空格
- 括号两边不要有空格;
- 不要在逗号,分号,冒号前面加空格,而是在后面加;
- 字典中冒号前面不用加空格,而是在后面加;
- 二元操作符两边都要加上一个空格,包括=、<、>、in、not in等等;
-
# True foo = 1000 # comment long_name = 2 # comment that should not be aligned
注释
- 一个函数除非是非常短小或者简单明了,否则都应该有注释;
-
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
-
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."""
类
字符串
TODO注释
- 为临时代码使用TODO注释, 它是一种短期解决方案;
-
TODO注释应该在所有开头处包含”TODO”字符串,紧跟着是用括号括起来的你的名字,email地址或其它标识符,然后是一个可选的冒号,接着必须有一行注释,解释要做什么。
# True # TODO([email protected]): Use a "*" here for string repetition. # TODO(Zeke) Change this to use relations.
导入格式
-
# False import os, sys # True import os import sys
语句
命名
Main
以上是关于Python风格规范的主要内容,如果未能解决你的问题,请参考以下文章