编程之禅
import this
The Zen of Python, by Tim Peters
Beautiful is better than ugly.
Explicit is better than implicit.
Simple is better than complex.
Complex is better than complicated.
Flat is better than nested.
Sparse is better than dense.
Readability counts.
Special cases aren't special enough to break the rules.
Although practicality beats purity.
Errors should never pass silently.
Unless explicitly silenced.
In the face of ambiguity, refuse the temptation to guess.
There should be one-- and preferably only one --obvious way to do it.
Although that way may not be obvious at first unless you're Dutch.
Now is better than never.
Although never is often better than *right* now.
If the implementation is hard to explain, it's a bad idea.
If the implementation is easy to explain, it may be a good idea.
Namespaces are one honking great idea -- let's do more of those!
PEP Python Enhancement Proposals Python增强规范
PEP8: PEP中的第八条:Style Guide for Python Code
- 缩进: Python在语法级别强制使用缩进保证代码的可读性和作用域
- 行最大长度:所有行限制的最大字符数为79,pycharm可以根据需求调整设置
- Editor-Code Style-Python-Hard wrap at
- 空行:两个函数/类之间空两行,类里面方法之间空一行
- 注释:与代码相矛盾的注释比没有注释还糟糕,代码更改时优先更新对应的注释
- 文档字符串 doc string
"""
This is a doc String
"""
- 块注释
# This is A
# This is B
- 行内注释
print("Hello world") # 打印Hello world
- 命名规范
- 变量:不要用小写的I, O,l,容易与数字混淆
- 函数: 下划线命名法
- 类: 帕斯卡命名法(又称大驼峰命名法)
- 字符串引号:
- 单引号与双引号作用相同,若字符串内容本身包含某种引号,则需要使用另一种引号来包裹字符串
- 三个双引号可以包裹一个区域的所有字符,通常用于定义doc string.
- 模块,包与import:
-
Python中一个py文件就是一个模块(module),模块名要小写
-
一个目录下多个模块可以组成一个包(package),必须要有__init__.py
-
import推荐习惯:
- 每一行import一个包的资源
- 不要from A import * ,可以import A 避免和本地资源同名
- 使用all来限制module 对外暴露的资源
- 使用import ... as ...来给导入的资源起别名
-
- 工程结构化
readme:对项目的整体介绍, 同时也是一份使用手册,需要市场维护更新,通常为README.rst/README.md
LICENSE:阐述该项目的许可说明和授权
setup.py:通过setup把核心代码打包发布
项目目录:存放项目的核心代码
requirements.txt:存放该项目所有依赖的第三方库
docs:包的参考文档
tests:所有代码测试都归存放于该目录下
makefile:用于项目的命令管理(开源项目广泛使用)根据项目需求添加其他的文件和目录
网友评论