PEP 8
全称为**Python Enhancement Proposal 8**,是一个为Python社区广泛接受的编码标准。它提供了一组规则和建议,用于编写清晰、一致且易于阅读的Python代码。以下是PEP 8的一些关键要点:
1. 缩进:使用4个空格进行缩进,不要使用制表符(Tab)。
if True:
print("True")
2. 行长度限制:每行代码的长度应限制在79个字符以内。
url = "https://blog.csdn.net/Withadream/article/details/138141879?csdn_share_tail=%7B%22type%22%3A%22blog%22%2C%22rType%22%3A%22artic
le%22%2C%22rId%22%3A%22138141879%22%2C%22source%22%3A%22Withadream%22%7D"
3. 空行:在顶级定义(如函数、类定义)之间使用两个空行,方法定义之间使用一个空行。
#代码注释
class pak()
#函数或方法
def run()
pass
4. 注释:在代码块的上方或下方留下必要的注释,而不是与代码同行。
#打印hello world
print("hello world")
5. 命名规范:
- 变量名和函数名应该全部小写,单词之间用下划线分隔(snake_case)。
- 类名应该使用驼峰命名法,即每个单词首字母大写(CamelCase)。
- 常量名应该全部大写,单词之间用下划线分隔(UPPER_CASE)。
6. 导入:每个导入语句单独占一行,尽量避免使用通配符导入(from module import *)。
import os
import sys
7. 空格:在二元运算符两边以及逗号、冒号、分号后面使用空格。
x = 5 + 3
y = x * 2
if y > 10:
print("y is greater than 10")
else:
print("y is not greater than 10")
8. 括号:在复杂表达式中使用括号来提高可读性。
result = (a + b) * (c - d) / e
9. 文档字符串(Docstrings):为所有公共模块、函数、类和方法提供文档字符串。
def add_numbers(a, b):
"""
This function adds two numbers and returns the result.
Parameters:
a (int): The first number to add.
b (int): The second number to add.
Returns:
int: The sum of the two numbers.
"""
return a + b
10. 编码声明:在文件开头添加UTF-8编码声明。
# -*- coding: utf-8 -*-