python笔记30-docstring注释添加变量
前言
python里面添加字符串注釋非常簡單,如何將變量放入 python 的函數注釋里面呢?
docstring也就是給代碼加注釋的內容了,python可以給函數,類、方法,模塊添加注釋內容,注釋標準格式一般是三個雙引號,如:"""美程序員槍擊4同事,竟因代碼不寫注釋?"""
docstring
先看一個簡單案例,在函數里面添加注釋內容,函數下方三個雙引號里面就可以寫該函數的注釋文檔了,如果需要調用此函數的注釋內容
# coding:utf-8def 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.pyhello類,實現xx功能 world方法,打印world如果函數里面帶有參數,也能給參數添加注釋
一個標準的函數注釋應該包含著幾個部分:
- 函數實現功能、
- 參數說明(需傳的參數是什么意思,參數類型)
- 函數返回值,沒return 默認為None
運行結果
登錄函數-連著輸入三個雙引號后回車,自動出來格式:param user: 用戶名,str:param psw: 密碼, str:return: resut是登錄結果, True or Falsedocstring添加變量
在docstring里面添加變量內容,變量的部分用%s代替,最后取值的時候,前面加一行代碼
用變量替換里面的%s部分
運行結果:
添加的注釋部分,這里是變量內容
還有一種寫法,可以先不在函數里面加內容,直接給函數.__doc__賦值
# coding:utf-8c = "這里是變量內容"def hello():print("hello world!")# 用hello.__doc__方法添加注釋內容 hello.__doc__ = """添加的注釋部分,%s"""%c a = hello.__doc__ print(a)運行結果:添加的注釋部分,這里是變量內容
使用裝飾器decorator
上面的方法雖然能實現添加變量注釋,但是不太優雅,接下來可以封裝一個函數,使用裝飾器來把變量傳入進去
# coding:utf-8def docstring_parameter(*sub):"""寫一個可以添加變量注釋的裝飾器"""def dec(obj):obj.__doc__ = obj.__doc__.format(*sub)return objreturn 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
總結
以上是生活随笔為你收集整理的python笔记30-docstring注释添加变量的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 3、数组和集合
- 下一篇: python - classs内置方法