python开发手册和函数文档的使用

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.

#查看函数文档

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值