PEP 8 规范

PEP 是 Python Enhancement Proposal 的缩写,翻译过来叫“Python 增强规范”。

缩进规范

PEP 8 规范告诉我们,请选择四个空格的缩进,不要使用 Tab,更不要 Tab 和空格混着用。 第二个要注意的是,每行最大长度请限制在 79 个字符。

空行规范

PEP 8 规定,全局的类和函数的上方需要空两个空行,而类的函数之间需要空一个空行。

空格规范

函数的参数列表中,调用函数的参数列表中会出现逗号,请注意逗号后要跟一个空格,这是英语的使用习惯,也能让每个参数独立阅读,更清晰。

冒号后面也要跟一个空格。

在#后、注释前加一个空格。

操作符,例如+,-,*,/,&,|,=,==,!=,请在两边都保留空格。不过与此对应,括号内的两端并不需要空格。

换行规范

控制每行的最大长度不超过 79 个字符,但是有时候,函数调用逻辑过长而不得不超过这个数字时按以下规范:

def solve1(this_is_the_first_parameter, this_is_the_second_parameter, this_is_the_third_parameter,

this_is_the_forth_parameter, this_is_the_fifth_parameter, this_is_the_sixth_parameter):

return (this_is_the_first_parameter + this_is_the_second_parameter + this_is_the_third_parameter +

this_is_the_forth_parameter + this_is_the_fifth_parameter + this_is_the_sixth_parameter)

def solve2(this_is_the_first_parameter, this_is_the_second_parameter, this_is_the_third_parameter,

this_is_the_forth_parameter, this_is_the_fifth_parameter, this_is_the_sixth_parameter):

return this_is_the_first_parameter + this_is_the_second_parameter + this_is_the_third_parameter + this_is_the_forth_parameter + this_is_the_fifth_parameter + this_is_the_sixth_parameter

(top_secret_func(param1=12345678, param2=12345678, param3=12345678, param4=12345678, param5=12345678).check()

.launch_nuclear_missile().wait())

top_secret_func(param1=12345678, param2=12345678, param3=12345678, param4=12345678, param5=12345678).check() .launch_nuclear_missile().wait()

1.通过括号来将过长的运算进行封装.

2.通过换行符来实现.

文档规范

import 尽量放在开头.

不要使用 import 一次导入多个模块.

from module import func 这样的语句,请确保 func 在本文件中不会出现命名冲突。或者通过 from module import func as new_func 来进行重命名,从而避免冲突。

注释规范

行注释并不是很推荐的方式。

文档描述

docstring 的写法,它是用三个双引号开始、三个双引号结尾。我们首先用一句话简单说明这个函数做什么,然后跟一段话来详细解释;再往后是参数列表、参数格式、返回值格式。

class SpatialDropout2D(Dropout):

"""Spatial 2D version of Dropout.

This version performs the same function as Dropout, however it drops

entire 2D feature maps instead of individual elements. If adjacent pixels

within feature maps are strongly correlated (as is normally the case in

early convolution layers) then regular dropout will not regularize the

activations and will otherwise just result in an effective learning rate

decrease. In this case, SpatialDropout2D will help promote independence

between feature maps and should be used instead.

Arguments:

rate: float between 0 and 1. Fraction of the input units to drop.

data_format: 'channels_first' or 'channels_last'.

In 'channels_first' mode, the channels dimension

(the depth) is at index 1,

in 'channels_last' mode is it at index 3.

It defaults to the `image_data_format` value found in your

Keras config file at `~/.keras/keras.json`.

If you never set it, then it will be "channels_last".

Input shape:

4D tensor with shape:

`(samples, channels, rows, cols)` if data_format='channels_first'

or 4D tensor with shape:

`(samples, rows, cols, channels)` if data_format='channels_last'.

Output shape:

Same as input

References:

- [Efficient Object Localization Using Convolutional

Networks](https://arxiv.org/abs/1411.4280)

"""

def __init__(self, rate, data_format=None, **kwargs):

super(SpatialDropout2D, self).__init__(rate, **kwargs)

if data_format is None:

data_format = K.image_data_format()

if data_format not in {'channels_last', 'channels_first'}:

raise ValueError('data_format must be in '

'{"channels_last", "channels_first"}')

self.data_format = data_format

self.input_spec = InputSpec(ndim=4)

命名规范

变量使用小写,通过下划线串联起来,例如:data_format、input_spec、image_data_set。唯一可以使用单字符的地方是迭代,比如 for i in range(n) 这种,为了精简可以使用。如果是类的私有变量,请记得前面增加两个下划线。

常量,最好的做法是全部大写,并通过下划线连接,例如:WAIT_TIME、SERVER_ADDRESS、PORT_NUMBER。

函数名,同样也请使用小写的方式,通过下划线连接起来,例如:launch_nuclear_missile()、check_input_validation()。

类名,则应该首字母大写,然后合并起来,例如:class SpatialDropout2D()、class FeatureSet()。

代码分解技巧

不写重复代码。

如:

if i_am_rich:

money = 100

send(money)

else:

money = 10

send(money)

都有send函数,可改为:

if i_am_rich:

money = 100

else:

money = 10

send(money)

代码嵌套过深:

def send(money):

if is_server_dead:

LOG('server dead')

return

else:

if is_server_timed_out:

LOG('server timed out')

return

else:

result = get_result_from_server()

if result == MONEY_IS_NOT_ENOUGH:

LOG('you do not have enough money')

return

else:

if result == TRANSACTION_SUCCEED:

LOG('OK')

return

else:

LOG('something wrong')

return

可改为:

def send(money):

if is_server_dead:

LOG('server dead')

return

if is_server_timed_out:

LOG('server timed out')

return

result = get_result_from_server()

if result == MONET_IS_NOT_ENOUGH:

LOG('you do not have enough money')

return

if result == TRANSACTION_SUCCEED:

LOG('OK')

return

LOG('something wrong')

以一个简单的二分搜索来举例说明。给定一个非递减整数数组,和一个 target,要求找到数组中最小的一个数 x,可以满足 x*x > target。一旦不存在,则返回 -1。

代码实现如果如下所示,那么可以再以一个函数只干一件事情的原则再优化下。

def solve(arr, target):

l, r = 0, len(arr) - 1

ret = -1

while l <= r:

m = (l + r) // 2

if arr[m] * arr[m] > target:

ret = m

r = m - 1

else:

l = m + 1

if ret == -1:

return -1

else:

return arr[ret]

print(solve([1, 2, 3, 4, 5, 6], 8))

print(solve([1, 2, 3, 4, 5, 6], 9))

print(solve([1, 2, 3, 4, 5, 6], 0))

print(solve([1, 2, 3, 4, 5, 6], 40))

优化如下:

def comp(x, target):

return x * x > target

def binary_search(arr, target):

l, r = 0, len(arr) - 1

ret = -1

while l <= r:

m = (l + r) // 2

if comp(arr[m], target):

ret = m

r = m - 1

else:

l = m + 1

return ret

def solve(arr, target):

id = binary_search(arr, target)

if id != -1:

return arr[id]

return -1

print(solve([1, 2, 3, 4, 5, 6], 8))

print(solve([1, 2, 3, 4, 5, 6], 9))

print(solve([1, 2, 3, 4, 5, 6], 0))

print(solve([1, 2, 3, 4, 5, 6], 40))

类中属性很多时可以抽出相同特性的单独作为类,如:

class Person:

def __init__(self, name, sex, age, job_title, job_description, company_name):

self.name = name

self.sex = sex

self.age = age

self.job_title = job_title

self.job_description = description

self.company_name = company_name

job_title , job_description , company_name 都与工作有关,表达是同一个意义实体,就可以抽出单独作为类:

class Person:

def __init__(self, name, sex, age, job_title, job_description, company_name):

self.name = name

self.sex = sex

self.age = age

self.job = Job(job_title, job_description, company_name)

class Job:

def __init__(self, job_title, job_description, company_name):

self.job_title = job_title

self.job_description = description

self.company_name = company_name

python如何提高程序可读性_Python规范:提高可读性相关推荐

  1. python windows桌面程序开发_Python 零基础入门

    Photo by Chris Ried on Unsplash Python 是一种易于学习又功能强大的编程语言.它提供了高效的高级数据结构,还有简单有效的面向对象编程.Python 优雅的语法和动态 ...

  2. python微信小程序抢购_Python实现微信小程序支付功能!Python确实强的一批!

    正文 由于最近自己在做小程序的支付,就在这里简单介绍一下讲一下用python做小程序支付这个流程.当然在进行开发之前还是建议读一下具体的流程,清楚支付的过程. 1.支付交互流程 2.获取openid( ...

  3. python网络爬虫程序技术_Python网络爬虫程序技术-中国大学mooc-题库零氪

    Python网络爬虫程序技术 - 中国大学mooc 已完结  94 项目1 爬取学生信息 1.2 Flask Web网站随堂测验 1.import flask app=flask.Flask(__n ...

  4. python微信小程序爬虫_Python爬取微信小程序实战(通用)

    背景介绍 最近遇到一个需求,大致就是要获取某个小程序上的数据.心想小程序本质上就是移动端加壳的浏览器,所以想到用Python去获取数据.在网上学习了一下如何实现后,记录一下我的实现过程以及所踩过的小坑 ...

  5. python编写小程序实例_python小程序开发实例

    商品和服务质量,是用户最关心的,运营者要保证质量,并把用户的完整信息的质量传达给用户,将影响用户的留存与转化的. 再小的店也有自己的品牌!一张小程序码可以让消费者看到你店里的详细经营情况和折扣优惠卷, ...

  6. python写完程序保存_Python学习笔记——文件处理

    1.文件路径 1.1 不同系统环境下的路径 1.2 当前工作目录 1.3 绝对路径和相对路径 1.4 新建文件夹-- os.makedirs() 2.文件的读写 2.1 打开文件 2.2 读写文件 3 ...

  7. python实现电脑程序自动化_python基于pywinauto实现PC客户端自动化

    一.前言 我们柠檬班的小可爱,在学完我们柠檬班自动化的课程之后,就掌握了接口自动化,web自动化,app自动化,这些工作中常用的自动化技能,在工作足以够应对90%以上的自动化需求了.不过近期也有部分小 ...

  8. python飞机大战程序导入_Python飞机大战项目的准备 导入Pygame最全攻略~

    1.导入pygame 首先是导入pygame模块,下面介绍的是pycharm中导入 先建立一个项目 左上角File->Setting->project:飞机大战项目(你自己的文件名字)-& ...

  9. python微信小程序实例_python+Mysql写微信小程序后台

    python比较简单,学了用处比较多,所以推荐写微信小程序的后台. (php.java等做后台太复杂了,学起来费劲) [0--假设] 1.Python开发环境已经搭好了,我这边喜欢用VScode. 2 ...

最新文章

  1. python高级开发面试题_python面试的100题(16)
  2. “〜”(波浪号/波浪形/旋转)CSS选择器是什么意思?
  3. 服务器端与客户端TCP连接入门(三:多线程)
  4. C# Console类学习笔记
  5. 9适应之力加多少攻击_剑盾铠之孤岛DLC新增内容大全! 宝可梦史上第一款DLC到底香不香(含试玩视频)...
  6. Android JNI入门第五篇——基本数据类型使用
  7. cad在线转低版本_为什么别人制图那么快?41个CAD实用技巧,3天轻松玩转CAD
  8. 整个电脑键盘被锁住了_希沃智能大屏按键说明,锁屏组合键你知道吗?小心被熊孩子锁住了...
  9. DOM对象和jquery对象相互转换
  10. 无法将W ndOWs配置为在,配置Wndows2000中的磁盘配额.doc
  11. JavaWeb项目架构之Kafka分布式日志队列
  12. 2020.12.23 随笔纪念粉笔数【2020】
  13. ArcGIS实验教程——实验四十三:ArcGIS栅格重分类(Reclass)案例详解
  14. linux怎么卸载home文件系统,Linux系统无法卸载文件系统该怎么办
  15. 如何旋转PDF页面并保存
  16. ​LeetCode刷题实战507:完美数
  17. O - Buns(混合背包)
  18. Mac/Windows下如何使用安卓模拟器开发UniApp
  19. Xposed获取微信个人信息
  20. 利用反向代理服务器,加快国内对国外主机的访问

热门文章

  1. 【hyddd驱动开发学习】DDK与WDK
  2. spring boot / cloud (二十) 相同服务,发布不同版本,支撑并行的业务需求
  3. deploy dubbox 到私有的 nexus 服务
  4. 【李宏毅2020 ML/DL】P51 Network Compression - Knowledge Distillation | 知识蒸馏两大流派
  5. 【数据结构笔记09】二叉树的定义、性质、实现
  6. 代码下移快捷键_收藏细看!最全面的通达信快捷键一览
  7. 7款效果惊人的HTML5/CSS3应用
  8. antd的table遍历之后添加合计行_付费?是不可能的!20行Python代码实现一款永久免费PDF编辑工具...
  9. linux 动态内存分配,具体来说,fork()如何处理Linux中malloc()动态分配的内存?
  10. java 二进制是什么类型_Java基础类型与其二进制表示