一、Docstring format
1、方法参数注释
File -> Settings -> Tools -> Python Integrated Tools -> Docstrings -> Docstring format
有5中风格,Plain、Epytext、reStructuredText、Numpy、Google。
在方法名下方输入三个双(单)引号,回车,自动生成;五种格式如下:
def docstrings_func_plain(parm_a, parm_b, parm_c):
"""
Plain 风格
"""
def docstrings_func_epytext(parm_a, parm_b, parm_c):
"""
Epytext 风格
@param parm_a: 参数a
@param parm_b: 参数b
@param parm_c: 参数c
@return: 结果a
"""
def docstrings_func_restructuredtext(parm_a, parm_b, parm_c):
"""
reStructuredText 风格
:param parm_a: 参数a
:param parm_b: 参数b
:param parm_c: 参数c
:return: 结果a
"""
def docstrings_func_numpy(parm_a, parm_b, parm_c):
"""
NumPy 风格
Parameters
----------
parm_a : 参数a
parm_b : 参数b
parm_c : 参数a
Returns
-------
result_a : 结果a
"""
def docstrings_func_google(parm_a, parm_b, parm_c):
"""
Google 风格
Args:
parm_a: 参数a
parm_b: 参数b
parm_c: 参数c
Returns:
result_a 结果a
"""
2、参数类型设置
Python是动态语言,使用动态类型(Dynamic Typed),即在运行时确定数据类型,变量使用之前不需要类型声明;对于一些已经确定类型的参数,加上类型的注释,可以借助pyCharm的方法类型检查功能,在书写代码时就能够提前发现错误。
File -> Settings -> Editor -> General -> Smart Keys -> Insert type placeholders in the documentation comment stub
二、File and Code Templates
File -> Setting -> Editor -> File and Code Templates
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Version : 0.1
Author : yx
Date : ${YEAR}-${MONTH}-${DAY}
"""
Live Templates
File -> Setting -> Editor -> Live Templates
# -*- coding: utf-8 -*-
三、Type Hints
def fun(x):
x.??? #can't hint or check
写函数的时候, 编译器并不知道形参x的类型, 所以函数体中调用x的字段与方法时, IDE 既不能作提示, 也不能作检查, 让人很捉急.
这是动态语言的通病. 所以很多人更喜欢java, c++.
但各种语言都是与时俱进的, javascript 有了 超集 TypeScript. 那么 python3 也在语言级别加入了 type hint. Provide a standard way of annotating a function’s parameters and return values.
python 仍是一门 动态语言, 所以这个注解加不加都可以.
1、函数签名
# 指定参数的类型, 函数的返回类型, 以及局部变量的类型
def foo(a: str, b: str) -> str:
return 'hi'
2、普通变量 及 类的成员字段
# 指定参数的类型, 函数的返回类型, 以及局部变量的类型
x = None # type: str
x= '' # 其实IDE已经能知道是str类型了
x:str=None #跟函数形参的hint类似, 以 ":+type" 构成
py2写法: 只能用 注释, 不能用 :type 表示
3、集合泛型
my_list:List[Student]=[] # py3
# py2
my_dict={} # type: Dict[int,str]
my_list_2=None # type: Tuple[int,Tuple[int]]
typeHint必须使用typing 包下相应的类.
对于层级较深的类, 需要注意相应的 import 路径, 会直接影响 IDE 的解析
import matplotlib
# 此时 IDE 无法定位到 axes, 因为它会去 matplotlib/__init__.py 中找 axes
x = x # type: matplotlib.axes.Axes
import matplotlib.axes
# 此时 IDE 才能正确定位, 因为它会去 matplotlib/axes/__init__.py 中找 Axes
x = x # type: matplotlib.axes.Axes