Home > Article > Backend Development > Compilation of knowledge points of Python coding standards
This article brings you relevant knowledge about Python, which mainly organizes issues related to coding standards. If you want to write python code well, you must understand python-related coding standards. With this With the blessing of , the code written can not only achieve the corresponding functions, but is also simple and easy to read, with clear logic. Let's take a look at it together. I hope it will be helpful to everyone.
[Related recommendations: Python3 video tutorial]
If you want to write python code well, you must understand python-related coding specifications. With this blessing, the code written can not only achieve the corresponding functions, but also be simple and easy to read, with clear logic. This section of the skill tree mainly shares the corresponding python coding specifications. Friends who are learning python, please read it carefully. It will definitely improve your python code writing! ! !
# -- coding: utf-8 --
import sys reload(sys) sys.setdefaultencoding('utf-8')
Do not add a semicolon at the end of the line, and do not use a semicolon. No. Put both commands on the same line.
No more than 80 characters per line
Except for the following situations:
Do not use backslashes to connect lines.
Python will implicitly connect lines enclosed in parentheses, square brackets, and curly braces.
Expressions within parentheses, square brackets, or curly braces are allowed to be broken into multiple physical lines without using backslashes. For example:
month_names = ['Januari', 'Februari', 'Maart', # These are the 'April', 'Mei', 'Juni', # Dutch names 'Juli', 'Augustus', 'September', # for the months 'Oktober', 'November', 'December'] # of the year
Implicit line splicing can be commented out. Indentation of subsequent lines does not affect program structure. Subsequent lines are also allowed to be blank lines.
If necessary, you can add an extra pair of parentheses around the expression.
If a text string does not fit on one line, you can use parentheses to implement implicit line concatenation
x = ('这是一个非常长非常长非常长非常长 ' '非常长非常长非常长非常长非常长非常长的字符串')
It is recommended to use the Python-mode default value of Emacs: 4 spaces per indentation level. Do not use tabs or mix tabs and spaces
Correct example code:
if a==0: print("正确") # 缩进4个空白占位 else: # 与if对齐 print("错误") # 缩进4个空白占位 或者 # 4 个空格缩进,第一行不需要 foo = long_function_name( var_one, var_two, var_three, var_four)
Incorrect example Code:
if a==0: print("正确") else: print("错误") print("end") # 错误的是这行代码前面加了一个空格 或者 # 2 个空格是禁止的 foo = long_function_name( var_one, var_two, var_three, var_four)
There are three forms of comments in Python: line comments, block comments, document comments
line Comments: Comments should explain what they do, not the code itself
n = input() m = input() t = n / 2 # t是n的一半 # 循环,条件为t*m/n 小于n while (t * m / (n + 1) < n): t = 0.5 * m + n / 2 # 重新计算t值 print(t)
块注释:
def FuncName(parameter1,parameter2): """ 描述函数要做的事情 :param parameter1: 参数一描述(类型、用途等) :param parameter2: 参数二描述 :return: 返回值描述 """
# 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 if i is a power of 2
文档注释:
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."""
class Class01: pass class Class02: def function_01(self): pass def function_02(self): pass
使用必要的空行可以增加代码的可读性,通常在顶级定义(如函数或类的定义)之间空两行,而方法定义之间空一行,另外在用于分隔某些功能的位置也可以空一行。
空格使用规则:
正确示例代码:
spam(ham[1], {eggs: 2}, []) if x == 4: print x, y x, y = y, x dict['key'] = list[index] def complex(real, imag=0.0): return magic(r=real, i=imag)
错误示例代码:
spam( ham[ 1 ] , { eggs: 2 } , [ ] ) if x == 4 : print x , y x , y = y , x dict ['key'] = list [index] def complex(real, imag = 0.0): return magic(r = real, i = imag)
模块名命名
# 正确 import decoder import html_parser # 不推荐 import Decoder
变量命名
count = 0 this_is_var = 0
常量或者全局变量命名
MAX_CLIENT = 100
函数命名
def run(): pass def run_with_env(): pass class Person(): def _private_func(): pass
类命名
class Farm(): pass class AnimalFarm(Farm): pass class _PrivateFarm(Farm): pass
类里面函数和方法参数
特别注意:
- 不要中英文混编
- 不要有a、b、c这种没有意义的命名
- 不要怕名字长就随便缩写,比如person_info 缩写成pi
- 不要用大小写区分变量类型,比如a是int类型,A是String类型
- 不要使用容易引起混淆的变量名
- bool变量⼀般加上前缀 is_ 如:is_success
- 变量名不要用系统关键字,如 dir type str等等
以下用下画线作前导或结尾的特殊形式是被公认的:
- _single_leading_underscore(以一个下画线作前导):例如,“from M import *”不会导入以下画线开头的对象。
- single_trailing_underscore_(以一个下画线结尾):用于避免与 Python 关键词的冲突,例如“Tkinter.Toplevel(master, class_='ClassName')”。
- __double_leading_underscore (双下画线):从 Python 1.4 起为类私有名。
- __double_leading_and_trailing_underscore__:特殊的(magic) 对象或属性,存在于
用户控制的(user-controlled)名字空间,例如:__init__、__import__ 或 __file__。
字符串引号规则:
正确使用示例:
Tim('Why are you hiding your eyes?') Bob("I'm scared of lint errors.") Juy('"Good!" thought a happy Python reviewer.')
正确使用例子:
import os import numpy import sys from types import StringType, ListType
错误使用例子:
import os, numpy, sys
from MyClass import MyClass from foo.bar.YourClass import YourClass
模块导入建议
示例 | 评价 |
from modu import * | 差, 不清楚具体从模块中导入了哪些内容 |
from modu import sqrt | 稍好 |
import modu import modu.sqrt |
最佳 , 调用的时候直接使用modu.sqrt能比较清楚的知道当前方法属于哪个模块 |
import os import sys |
推荐 |
import os, sys |
不推荐 |
from subprocess import Popen, PIPE | 推荐 |
主功能应该放在一个main()函数中。
在Python中,pydoc以及单元测试要求模块必须是可导入的。代码应该在执行主程序前总是检查 if __name__ == '__main__'
, 这样当模块被导入时主程序就不会被执行。
def main(): ... if __name__ == '__main__': main()
如果要将 RCS 或 CVS 的杂项包含在你的源文件中,按如下格式操作:
__version__ = "$Revision: 1.4 $" # $Source: E:/cvsroot/python_doc/pep8.txt,v $
对于 CVS 的服务器工作标记更应该在代码段中明确出它的使用说明,如在文档最开始的版权声明后应加入如下版本标记:
# 文件:$id$ # 版本:$Revision$
这样的标记在提交给配置管理服务器后,会自动适配成为相应的字符串,如:
# 文件:$Id: ussp.py,v 1.22 2004/07/21 04:47:41 hd Exp $ # 版本:$Revision: 1.4 $
这些应该包含在模块的文档字符串之后,所有代码之前,上下用一个空行分割。
【相关推荐:Python3视频教程 】
The above is the detailed content of Compilation of knowledge points of Python coding standards. For more information, please follow other related articles on the PHP Chinese website!