”””美程序员枪击4同事,竟因代码不写注释?”””
python里面添加字符串注释非常简单,如何将变量放入 python 的函数注释里面呢?docstring也就是给代码加注释的内容了,python可以给函数,类、方法,模块添加注释内容,注释标准格式一般是三个双引号(或三个单引号)
先看一个简单案例,在函数里面添加注释内容,函数下方三个双引号里面就可以写该函数的注释文档了,如果需要调用此函数的注释内容
# 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
如果函数里面带有参数,也能给参数添加注释 一个标准的函数注释应该包含着几个部分:
print(login.doc)
运行结果
登录函数-连着输入三个双引号后回车,自动出来格式
:param user: 用户名,str
:param psw: 密码, str
:return: resut是登录结果, True or False
# docstring添加变量
在docstring里面添加变量内容,变量的部分用%s代替,最后取值的时候,前面加一行代码
用变量替换里面的%s部分
c = “这里是变量内容”
def hello(): “””添加的注释部分,%s””” print(“hello world!”)
hello.doc %= c # 先用变量c替换里面的%s部分 a = hello.doc print(a)
运行结果:
添加的注释部分,这里是变量内容
还有一种写法,可以先不在函数里面加内容,直接给函数.__doc__赋值
c = “这里是变量内容”
def hello(): print(“hello world!”)
hello.doc = “””添加的注释部分,%s”””%c a = hello.doc print(a)
运行结果:添加的注释部分,这里是变量内容
# 使用装饰器decorator
上面的方法虽然能实现添加变量注释,但是不太优雅,接下来可以封装一个函数,使用装饰器来把变量传入进去
def docstringparameter(*sub): “””写一个可以添加变量注释的装饰器””” def dec(obj): obj.doc = obj._doc.format(*sub) return obj return dec
@docstring_parameter(“打印hello world”) def hello(): “”” 实现功能:{0}””” print(“hello world!”)
a = hello.doc print(a)
@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