master
/ 1.6 编码与命名规范.ipynb

1.6 编码与命名规范.ipynb @masterview markup · raw · history · blame

Notebook

1.6 编码与命名规范

1.6.1 编码规范

一般情况下,Python编程遵循__PEP8规范__,下面仅给出其中一些主要的约定。</font>

1. 编码: 在Python 3中,如无特殊情况, 文件一律使用__UTF-8 编码__。</font>

2. 代码缩进: 建议使用 __4 个空格__进行缩进,__制表符__只能用于与同样使用制表符缩进的代码保持一致。Python 3__不允许混合使用__空格和制表符的缩进。</font>

In [1]:
for i in range(5):
    print('Hello python')  # 缩进4个空格
Hello python
Hello python
Hello python
Hello python
Hello python

3. 行的最大长度: 每行代码尽量少于__80 个字符__ ,在特殊情况下可以超过 80个,但最长不超过 120个。没有结构化限制的大块文本(文档字符或者注释),每行的最大字符数限制在72个。</font>

In [ ]:
import math

result = 0
for i in range(3):
    result = result + ((2 * 2 ** 0.5)) * (math.factorial(4 * i) * (1103 + 26390 * i)) / (math.pow(math.factorial(i), 4) * math.pow(396, 4 * i)) / 9801
pi = 1 / result
print(pi)

超80字符时换行书写:

In [1]:
import math

result = 0
for i in range(3):
    result = result + ((2 * 2 ** 0.5)) * (math.factorial(4 * i) * (1103 + 26390 * i)) / (
                math.pow(math.factorial(i), 4) * math.pow(396, 4 * i)) / 9801
pi = 1 / result
print(pi)
3.141592653589793

4. 引号: 在Python中,单引号和双引号字符串是相同的。当一个字符串中包含单引号或者双引号字符的时候,使用__与最外层不同__的符号来__避免使用反斜杠__,从而提高可读性。 对于三引号字符串,总是使用双引号字符来与PEP文档字符串约定保持一致。 __文档字符串__ (docstring) 使用三对双引号 """......"""。</font>

用转义字符:\' 被解析为单引号: ',\" 被解析为双引号: "

In [4]:
print('Python is TIOBE\'s Programming Language of the Year 2021!')

print("毛主席说\"红军不怕远征难\"。")

推荐用与字符串中引号不同的定界符,避免使用转义字符:

In [5]:
print("Python is TIOBE's Programming Language of the Year 2021!")

print('毛主席说"红军不怕远征难"。')

5. 空行: 模块级函数和类定义之间空两行,类成员函数之间空一行。 使用多个空行分隔多组相关的函数,函数中可以使用空行分隔出逻辑相关的代码。

In [ ]:
def any(*args, **kwargs): # real signature unknown
    """Return True if bool(x) is True for any x in the iterable."""
    pass

def ascii(*args, **kwargs): # real signature unknown
    """Return an ASCII-only representation of an object."""
    pass

def bin(*args, **kwargs): # real signature unknown; NOTE: unreliably restored from __doc__ 
    """Return the binary representation of an integer."""
    pass

    

6. import 语句:

import总是位于文件的__顶部__,在模块注释和文档字符串之后,在模块的全局变量与常量之前。
导入应该按照以下顺序分组:
1.标准库导入
2.相关第三方库导入
3.本地应用/库特定导入

import 语句应该分行书写,在每一组导入之间加入空行。</font>

推荐的写法

In [ ]:
# 推荐的写法
import turtle
import math
from math import sqrt,pow

不推荐的写法,一般不建议在同一行内导入多个不同的模块

In [ ]:
# 不推荐的写法
import turtle, math

7. 空格: (1)在二元运算符+、-、*、/、=、+=、==、>、<、in、is not、and等两边各空一格。

In [7]:
# 二元符号两端不加空格不属于错误,但不符合规范
# 以下为格式示例,部分变量未定义,不要运行
i=i+1
total=total+i
area=PI*r**2
x=(-b+sqrt(b**2-4*a*c))/(2*a)
In [ ]:
# 推荐的程序语句写法示例
i = i + 1
total = total + i
area = PI * r ** 2
x = (-b + sqrt(b ** 2  4 * a * c)) / (2 * a)

(2)函数的参数列表中,逗号之后要有空格。

In [ ]:
# 推荐的写法
def complex(real, imag):
    pass
In [ ]:
# 不推荐的写法
def complex(real,imag):
   pass

(3)左括号之后,右括号之前不要加多余的空格。

In [ ]:
# 推荐的写法
spam(ham[1], {eggs: 2})
In [ ]:
# 不推荐的写法
spam( ham[1], { eggs : 2 } )

(4)字典对象的左括号之前不要多余的空格。

In [ ]:
# 推荐的写法
dict['key'] = list[index]
In [ ]:
#不推荐的写法
dict ['key'] = list [index]

(5)不要为对齐赋值语句而使用的额外空格。

In [3]:
# 推荐的写法
x = 5
y = 10
long_variable = 20
In [2]:
# 不推荐的写法
x             = 5
y             = 10
long_variable = 20

8. 换行: Python 支持括号内的换行。这时有两种情况:

(1) 第二行缩进到左括号的起始处。

In [ ]:
wc = WordCloud(font_path = 'msyh.ttc',    # 中文字体,须修改路径和字体名
               background_color = 'White',# 设置背景颜色
               max_words = 150,           # 设置最大词数
               mask = graph,
               max_font_size = 100,       # 设置字体最大值
               random_state = 20,        # 设置有多少种随机状态,即配色方案
               scale = 1)

(2) 第二行缩进 4 个空格,适用于起始括号就换行的情形。

In [ ]:
def function_student(
    studentNumber,
    studentName,
    birthdate,
    ):
    

(3) 使用反斜杠“\”换行
一般使二元运算符“+ 、-”等应出现在行末;

In [ ]:
x = (-b + math.sqrt(b ** 2 - 4  a  c))/(2 * a) + \
(-b - math.sqrt(b ** 2 + 4  a  b))/(2 * b)

长字符串也可以用此法换行。

In [8]:
print('Hello World!'\
'I am Python')

# 代码在两行,输出在一行:Hello World!I am Python

__禁止复合语句__,即禁止一行中包含多个语句:</font>

In [ ]:
# 正确的写法

do_first()
do_second()
do_third()
In [ ]:
# 禁用的写法,不报错,不规范

do_first();do_second();do_third()
In [ ]:
# 禁用的写法
a = 50; b = 100; c = 200        # 不报错,可执行,不建议使用
print(a,b,c)                    #  50 100 200

if/for/while/def等以冒号结尾的语句要__换行__

In [ ]:
# 推荐的写法
if i == True:
print('Hello World!')
In [ ]:
# 不推荐的写法
if i == True: print('Hello World!')
    
  1. 文档注释(docstring)
    文档注释的规范中最基本的两点:
    (1)所有的公共模块、函数、类、方法,都应该写文档注释。私有方法不要求写文档注释,但应该在 def 后提供一个块注释来说明。
    (2)文档注释的结束"""应该独占一行,除非此文档注释只有一行。
In [ ]:
class _EnumDict(dict):
    """
    Track enum member order and ensure member names are not reused.
    EnumMeta will use the names found in self._member_names as the
    enumeration member names.
    """
    pass
    ......

    def _is_descriptor(obj):
        """Returns True if obj is a descriptor, False otherwise."""
        pass
        ......

1.6.2 命名规范

Python中的命名可以使用__大(小)写字母____数字____下划线(_)__,数字不做首字母,下划线开头的变量有特殊含义,一般不用。</font>

In [ ]:
def f1(a):
    if a % 400 == 0 or a % 100 != 0 and a % 4 == 0: 
        return True
    else:
        return False



def f2(b):
    c = int(b[:4])  
    d = int(b[4:6])  
    e = int(b[-2:])   
    f = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31] 
    g = sum(f[:d - 1]) + e  
    if f1(c) and d >= 2:    
        g = g + 1    
    return g      



if __name__ == '__main__':
    h = input()     
    print(f2(h)) 
In [ ]:
def leap(year: int) -> bool:
    """接收一个正整数参数,判定该数字对应的年份是否是闰年
    返回布尔值,是闰年时返回True,不是闰年时返回False
    """
    # 年份能被400的整除或年份能被4整除但不能被100整除的是闰年
    if year % 400 == 0 or year % 100 != 0 and year % 4 == 0:  # 是闰年时
        return True
    else:
        return False



def get_days(date_str: str) -> int:
    """接收一个表示年月日的整数字符串为参数,返回这个日期是该年的第多少天,返回整数"""
    year = int(date_str[:4])    # 获取字符串中的年份数值,整数
    month = int(date_str[4:6])  # 获取字符串中的月份数值,整数
    day = int(date_str[-2:])    # 获取字符串中的月份数值,整数
    days_ls = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]  # 各月天数的列表
    which_day_of_today = sum(days_ls[:month - 1]) + day  # 前month-1个月的总天数加当前日期
    if leap(year) and month >= 2:                        # 若是闰年且月份数大于2
        which_day_of_today = which_day_of_today + 1      # 加上闰年2月多的一天
    return which_day_of_today                            # 返回是该年的第多少天



# 以模块模式运行时,执行以下分支中的代码
if __name__ == '__main__':
    date = input()         # 输入一个表示年月日的整数字符串,此处要求输入是合法的年月日数值
    print(get_days(date))  # 输出这个日期是该年第多少天

(1)类:使用首字母大写单词串,UpperCamelCase,首字母大写的驼峰命名法

In [ ]:
class MyClass():
    pass
    ...

(2)函数和方法:小写单词+下划线,lowercase_with_underscores。

In [ ]:
def is_prime():
    pass
    ...

(3)变量:由下划线连接各个小写字母的单词

In [ ]:
color = 'red'
user_name = '李明'
this_is_a_variable = 10

(4)常量:常量名所有字母大写,由下划线连接各个单词

In [4]:
PI = 3.141592653589793
E = 2.718281828459045
MAX_OVERFLOW = 1.7976931348623157e+308
DAYS_OF_YEAR = 365

(5)异常:以“Error”作为后缀。

In [ ]:
# 不要运行此单元,只用于显示
SyntaxError          # 语法错误
NameError            # 未声明/未初始化的对象(没有属性)
SystemError          # 一般的解释器系统错误
ValueError           # 传入无效的参数,或传入一个调用者不期望的值,即使值的类型是正确的
IndentationError     # 缩进错误(代码没有正确对齐)
ImportError          # 导入模块/对象失败(路径问题或名称错误)
ModuleNotFoundError  # 模块不存在
ZeroDivisionError    # 除(或取模)零
OverflowError        # 数字运算超出最大限制
AttributeError       #对象没有这个属性
IndexError           # 索引超出序列边界,如x只有10个元素,序号为0-9,程序中却试图访问x[10]
KeyError             # 映射中没有这个键(试图访问字典里不存在的键)
TypeError            # 对类型无效的操作
TabError             # Tab和空格混用
RuntimeError         # 一般的运行时错误

(6)文件名:全小写,可使用下划线。

xrd.csv poem.txt tang_poem.txt

(7)包与模块:简短的、小写字母的名字。

matplotlib pandas seaborn qrcode pyplot.py algorithms.py

命名应当尽量使用完整的单词,缩写的情况有如下两种:

(1)常用的缩写,如XML、ID等,在命名时也应只大写首字母。

In [ ]:
XmlParser
Id_code

(2)命名中含有长单词,对某个单词进行缩写。这时应使用约定成俗的缩写方式。

In [ ]:
function 缩写为 fn
text 缩写为 txt
object 缩写为 obj
count 缩写为 cnt
number 缩写为 num

特定命名方式: 主要是指 xxx 形式的系统保留字命名法。 项目中也可以使用这种命名,它的意义在于这种形式的变量是只读的,这种形式的类成员函数尽量不要重载。

In [ ]:
class Base(object):
    def init(self, id, parent=None):
        self.id = id
        self.parent = parent

    def message(self, msgid):
        pass

# 其中 id、parent 和 message 都采用了系统保留字命名法。