簡體   English   中英

為什么我不能將格式函數與docstrings一起使用?

[英]Why can't I use the format function with docstrings?

我有一個像這樣開始的函數:

def apply_weighting(self, weighting):
    """
    Available functions: {}
    """.format(weightings)

我想要的是docstring打印可用加權函數的字典。 但是在檢查函數時,它聲明沒有可用的文檔字符串:

In [69]: d.apply_weighting?
Type:       instancemethod
String Form:<bound method DissectSpace.apply_weighting of <dissect.DissectSpace instance at 0x106b74dd0>>
File:       [...]/dissect.py
Definition: d.apply_weighting(self, weighting)
Docstring:  <no docstring>

怎么會? 是否無法格式化文檔字符串?

Python解釋器查找字符串文字。 不支持添加.format()方法調用,不支持函數定義語法。 編譯器解析文檔字符串而不是解釋器,並且當時不能使用weightings等變量; 目前沒有代碼執行。

您可以在事后更新文檔字符串:

def apply_weighting(self, weighting):
    """
    Available functions: {}
    """

apply_weighting.__doc__ = apply_weighting.__doc__.format(weightings)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM