Python(十七):python的编程规范、PEP8


🔗python全部编程规范的索引
🔗 python编程规范之PEP8

PEP8

让 Python 更易阅读,换句话,增强代码可读性。

pycharm 默认设置了 PEP8 检查。

缩进

python 的缩进:Tab、双空格、四空格、空格和 Tab 混合等。
PEP8:四空格的缩进
实际中,写代码缩进用制表符, 🔗设置1个制表符=4个空格

行长

PEP8:行最大长度为 79 个字符,包括注释

🔗设置行长标志(一条竖线)

空行

PEP8:

  • 全局的类和函数间:两个空行
  • 类中的函数间:一个空行
  • 函数内部:可以一个空行,区分不同的代码块
  • 每个代码文件的最后一行为空行,并且只有这一个空行

空格

PEP8:

  • [1, 2, 3] 列表等的逗号后要有一个空格
  • {'a': 1, 'b':, 2} 字典的冒号后有一个空格
  • # 这是注释 #号后有一个空格
  • x = (1 + 2) * 3 操作符两边有空格,括号两边没有空格
  • fun(x=1, y=2) 函数参数中的等号两边不要有空格

换行规范

list、dist、tuple 元素太多


li = {
    'name': 'Bob',
    'age': 18,			# 最后一个加 逗号
    }
li = [
    5,
    15,
    ]

函数参数太多

def func(parameter_0, parameter_1, parameter_2,      
        parameter_3, parameter_4, parameter_5):		# 区分pass,两个缩进,与第一行参数对齐
    pass    
    
func(1, 2, 3,
    4, 5, 6)       # 一个缩进

class Model(network.Network):
    def fit(self,
            x=None,
            y=None,
            batch_size=None,
            epochs=1,
            verbose=1,
            callbacks=None,
            validation_split=0.,
            validation_data=None,
            shuffle=True,
            class_weight=None,
            sample_weight=None,
            initial_epoch=0,
            steps_per_epoch=None,
            validation_steps=None,
            validation_freq=1,
            max_queue_size=10,
            workers=1,
            use_multiprocessing=False,
            **kwargs):
        # Legacy support
        if 'nb_epoch' in kwargs:
            logging.warning(
                'The `nb_epoch` argument in `fit` has been renamed `epochs`.')
            epochs = kwargs.pop('nb_epoch')
        if kwargs:
            raise TypeError('Unrecognized keyword arguments: ' + str(kwargs))
        self._assert_compile_was_called()

        func = self._select_training_loop(x)
        return func.fit(
            self,
            x=x,
            y=y,
            batch_size=batch_size,
            epochs=epochs,
            verbose=verbose,
            callbacks=callbacks,
            validation_split=validation_split,
            validation_data=validation_data,
            shuffle=shuffle,
            class_weight=class_weight,
            sample_weight=sample_weight,
            initial_epoch=initial_epoch,
            steps_per_epoch=steps_per_epoch,
            validation_steps=validation_steps,
            validation_freq=validation_freq,
            max_queue_size=max_queue_size,
            workers=workers,
            use_multiprocessing=use_multiprocessing)

字符串太长

推荐用:+=

# += 拼接 
s = 'Youth is not a time of life; it is a state of mind;'
s += ' it is not a matter of rosy cheeks, red lips and supple knees; '
s += 'it is a matter of the will, a quality of the imagination,'
s += ' a vigor of the emotions; it is the freshness of the deep springs of life.'
print(s)


# 加 \ 换行
s = 'Youth is not a time of life; it is a state of mind;' \
    ' it is not a matter of rosy cheeks, red lips and supple knees; ' \
    'it is a matter of the will, a quality of the imagination,' \
    ' a vigor of the emotions; it is the freshness of the deep springs of life.'
print(s)

打印太长

推荐用:+

# + 拼接,要紧跟处理元素,不要放在行末
print(s + 'Youth is not a time of life; it is a state of mind;' 
      + ' it is not a matter of rosy cheeks, red lips and supple knees; ' 
      + 'it is a matter of the will, a quality of the imagination,' 
      + ' a vigor of the emotions; it is the freshness of the deep springs of '  
      + 'life.')
      
      
# 直接换行
print(s +'Youth is not a time of life; it is a state of mind;'
      ' it is not a matter of rosy cheeks, red lips and supple knees; '
      'it is a matter of the will, a quality of the imagination,'
      ' a vigor of the emotions; it is the freshness of the deep springs of '
      'life.')

命名

规律举例
变量名、函数名、模块名(.py文件名)全小写、下划线a_student 、get_name()
常量全大写、下划线MAX_NUM
类名驼峰命名:首大写,每个单词都首大写MaleStudent

import

EPE8:

  • import 都放在文件头部
  • 不要使用 import 一次导入多个模块,如import time, os不可
  • import 只能导入包、模板,如不要from numpy import array,而是import numpy,代码中用numpy.array()array()

文档字符串

函数、类、模块(.py文件)均要写文档字符串,进行说明

def func(x, y):
	"""
	参数:
		x: 参数的意义、格式(数据类型)
		y: 参数的意义、格式(数据类型)
	输入:
		举例
	输出:
		返回值和格式
	"""

注释

  • 文档字符串用 “”",其余注释用 #
  • 对于代码的注释,写在代码前面(与代码相同缩进),不要写行注释
def fun():
	x = 1
	y = 2

	# 这是注释
	# 这是注释
	# 这是注释
	z = x + y			# 注释不要写在这

python编辑器的设置

  1. 快捷键
    选中代码块,缩进和取消(tab 和 shift+tab)
    选中代码块,注释和取消( Ctrl+/ 和 Ctrl+/)

其它

读者体验 > 编程者体验 > 机器体验

linter 工具:Pylint,https://www.pylint.org/,检查代码风格/错误的小工具
要将自定义的的代码规范写进 pylint 中

  • 当判断对象是否为 None 时,必须显示的写 is None。除了 bool 类型,其它都要显示的判断,==[]、!=0
  • 遍历dicr,for k in d:for k in d.keys():好,因为 d.keys() 要占用内存
  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值