python笔记30-docstring注释添加变量

前言

python里面添加字符串注释非常简单,如何将变量放入 python 的函数注释里面呢?
docstring也就是给代码加注释的内容了,python可以给函数,类、方法,模块添加注释内容,注释标准格式一般是三个双引号,如:"""美程序员枪击4同事,竟因代码不写注释?"""

docstring

先看一个简单案例,在函数里面添加注释内容,函数下方三个双引号里面就可以写该函数的注释文档了,如果需要调用此函数的注释内容

# coding:utf-8

def yoyo():
    """函数功能:打印hello world!"""
    print("hello world!")


a = yoyo.__doc__
print(a)

运行结果:函数功能:打印hello world!

类、方法和模块也能添加注释内容

# coding:utf-8

"""
这个是该模块的注释内容:hello.py
"""

class Hello():
    """hello类,实现xx功能"""

    def world(self):
        """world方法,打印world"""
        print("world")

a = __doc__  # 获取模块的docstring内容
print(a)

b = Hello.__doc__   # 获取类的docstring内容
print(b)

c = Hello.world.__doc__  # 获取方法的docstring内容
print(c)

运行结果

这个是该模块的注释内容:hello.py

hello类,实现xx功能
world方法,打印world

如果函数里面带有参数,也能给参数添加注释
一个标准的函数注释应该包含着几个部分:

  • 函数实现功能、
  • 参数说明(需传的参数是什么意思,参数类型)
  • 函数返回值,没return 默认为None
def login(user, psw):
    """
    登录函数-连着输入三个双引号后回车,自动出来格式
    :param user: 用户名,str
    :param psw: 密码, str
    :return: resut是登录结果, True or False
    """
    print(user)
    print(psw)
    resut = "登录结果"
    return resut

print(login.__doc__)

运行结果

    登录函数-连着输入三个双引号后回车,自动出来格式
    :param user: 用户名,str
    :param psw: 密码, str
    :return: resut是登录结果, True or False

docstring添加变量

在docstring里面添加变量内容,变量的部分用%s代替,最后取值的时候,前面加一行代码
用变量替换里面的%s部分

# coding:utf-8

c = "这里是变量内容"

def hello():
    """添加的注释部分,%s"""
    print("hello world!")

hello.__doc__ %= c  # 先用变量c替换里面的%s部分
a = hello.__doc__
print(a)

运行结果:
添加的注释部分,这里是变量内容

还有一种写法,可以先不在函数里面加内容,直接给函数.__doc__赋值

# coding:utf-8

c = "这里是变量内容"

def hello():
    print("hello world!")

# 用hello.__doc__方法添加注释内容
hello.__doc__ = """添加的注释部分,%s"""%c
a = hello.__doc__
print(a)

运行结果:添加的注释部分,这里是变量内容

使用装饰器decorator

上面的方法虽然能实现添加变量注释,但是不太优雅,接下来可以封装一个函数,使用装饰器来把变量传入进去

# coding:utf-8

def docstring_parameter(*sub):
    """写一个可以添加变量注释的装饰器"""
    def dec(obj):
       obj.__doc__ = obj.__doc__.format(*sub)
       return obj
    return dec


# 案例1-添加一个参数
@docstring_parameter("打印hello world")
def hello():
    """ 实现功能:{0}"""
    print("hello world!")

a = hello.__doc__
print(a)

# 案例2-添加2个参数

@docstring_parameter("打印hello", "打印world")
def world():
    """ 实现功能:{0}, {1}"""
    print("hello world!")

b = world.__doc__
print(b)

运行结果:
实现功能:打印hello world
实现功能:打印hello, 打印world

参考文档:https://ask.helplib.com/python-2.7/post_1277206

python自动化交流 QQ群:779429633

原文地址:https://www.cnblogs.com/yoyoketang/p/9719147.html