1.python中通过是用help函数我们可以快速的查看函数的使用文档,例如:
help(print)
Help on built-in function print in module builtins:
print(*args, sep=' ', end='\n', file=None, flush=False)##函数原型
Prints the values to a stream, or to sys.stdout by default.
##函数的功能介绍
##各个参数的类型及作用
sep
string inserted between values, default a space.
end
string appended after the last value, default a newline.
file
a file-like object (stream); defaults to the current sys.stdout.
flush
whether to forcibly flush the stream.
通过使用字符串来创建函数文档
def exchange(dollar, rate=7.32):
"""
功能:汇率转换,美元->人民币
- dollar 美元数量
- rate 汇率,默认值是7.32
返回值:
- 人民币的数量
"""
return dollar * rate
print(exchange(20))
##146.4
help(exchange)
## exchange(dollar, rate=7.32)
## 功能:汇率转换,美元->人民币
## - dollar 美元数量
## - rate 汇率,默认值是7.32
## 返回值:
## - 人民币的数量
2.类型注释:
函数中冒号后是对函数参数的注释,箭头后是对返回值的注释,但是要注意的是即使不按注释输入,程序依然不会报错。在注释后使用赋值号依然可以使用默认参数.
def times(s:str, n:int = 5) -> str:
return s * n
print(times("Cloud"))
## CloudCloudCloudCloudCloud
print(times("Cloud", 3))
## CloudCloudCloud
同理我们也可以对输入序列以及其参数参数类型进行注释:
def times(s:list[int], n:int = 5) -> list:
return s*n
print(times([1, 2, 3]))
## [1, 2, 3, 1, 2, 3, 1, 2, 3, 1, 2, 3, 1, 2, 3]
def times1(s:dict[str, int], n:int = 5) -> list:
return list(s.keys())*n
print(times1({'a':1, 'b':2, 'c':3}))
## ['a', 'b', 'c', 'a', 'b', 'c', 'a', 'b', 'c', 'a', 'b', 'c', 'a', 'b', 'c']
3.内省
def times(s:dict[str, int], n:int = 5) -> list:
return list(s.keys())*n
print(times.__name__)
## times
# 查看函数名称
print(times.__annotations__)
## {'s': dict[str, int], 'n': <class 'int'>, 'return': <class 'list'>}
# 查看函数的类型注释
print(print.__doc__)
##Prints the values to a stream, or to sys.stdout by default.
##
## sep
## string inserted between values, default a space.
## end
## string appended after the last value, default a newline.
## file
## a file-like object (stream); defaults to the current sys.stdout.
## flush
## whether to forcibly flush the stream.
#查看函数文档