之前一直使用 sublime 编辑器编写 python 代码,后面使用 vs code 编辑器打开项目文件时,发现有很多规范上的问题。特地总结一下编写 python 代码规范,编写代码时还是需要严格遵守代码规范。
若需要阅读 Google 官方 python 代码风格指导文档,请点击 这里 。 对于以下文档中没有提到规范,你可以使用 python 模块 pylint 检查你的 python 代码是否符合规范。
- pip3 install pylint
在这里推荐使用 VS code 编辑器,安装 pylint 后。打开你的项目文件,查看是否存在代码规范问题。
- # -*- coding: utf-8 -*-
- # 正确的写法
- import sys
- import time
- from subprocess import Popen, PIPE
-
- # 不推荐的写法
- import sys, time
- # 正确的写法
- from foo.bar import Bar
-
- # 不推荐的写法
- from ..bar import Bar
- # -*- coding: utf-8 -*-
- """
- This is a Test program
- """
- import sys
- # 以 flask 库的 wrappers.py 文件为例,以下为该文件导入的包
- from werkzeug.exceptions import BadRequest
- from werkzeug.wrappers import Request as RequestBase, Response as ResponseBase
-
- from flask import json
- from flask.globals import current_app
- import xlrd
-
- # 代码不需要 xlrd 库,不需要写以上 import xlrd 代码
- def test():
- pass
- # 正确的写法
- i = i + 1
- submitted += 1
- x = x * 2 - 1
- hypot2 = x * x + y * y
- c = (a + b) * (a - b)
- # 正确的写法
- def plus_func(a, b):
- pass
- # 正确写法
- def plus_func(a=1, b):
- pass
- # 正确的写法
- spam(ham[1], {eggs: 2})
-
- # 不推荐的写法
- spam( ham[1], { eggs : 2 } )
- # 正确的写法
- dict['key'] = list[index]
-
- # 不推荐的写法
- dict ['key'] = list [index]
- # 正确的写法
- a = 1
- b = 33
- name = 'test'
- # 不正确的写法
- a = 1
- b = 33
- name = 'test'
python 支持括号内的换行。
docstring 中文可称为文档字符串。python 独有的一种注释方式。通过这样注释的字符串能够被对象的__doc__方法自动获取。
- # docstring 写在如下位置
- class Test():
- """class Test
- """
- def func():
- """func"""
- pass
推荐使用 “with”语句处理文件
- # 推荐用法
- with open("hello.txt") as hello_file:
- for line in hello_file:
- print line
- main.py
- flask
- class WinMain:
- PERSON_NAME = "Fan"
- name = ''
- your_name = 'Alan'
- self._your_name = ''
- __name__ = ''
- class Test():
- """Test"""
- # protected 型变量
- _name = 'protected variable'
- # 私有 private 变量
- __info = 'private variable'
- def _func1():
- """protected"""
- print("这是一个 protected 方法")
- def __func2():
- """private 私有"""
- print("这是一个 private 方法")
- def print_func():
- """public 公共"""
- print('这个一个 public 方法')
- def test_method():
- is_true = True
- has_name = True
- # 推荐的写法
- def test():
- print('行注释') # 打印
- # 块注释
- # 块注释
- #
- # 块注释
- # 块注释
在关键代码部分可以使用更加项目的注释
- app = create_app(name, options)
-
- # =============================
- # 请不要修改此部分的代码
- # =============================
-
- if __name__ == "__main__":
- app.run
- # -*- coding: utf-8 -*-
- """Example docstring
- flask.app
- ~~~~~~~~~
-
- This module implements the central WSGI application object.
-
- :copyright: © 2010 by the Pallets team.
- :license: BSD, see LICENSE for more details.
- """
类和函数的头部定义的 docstring。具体描述其具体内容以及实现的功能,解释具体参数和返回值等。
- class WinMain(QtGui.QMainWindow):
- """程序主窗口类,主要实现生成 ui 界面。
- 另外包括
- """
- def init_config(self):
- """初始化工具程序界面的配置参数,
- 没有返回值
- """
- pass