這是我在做什么:
class Foo:
def __init__(self, **kwargs):
"""
docstring of Foo.
"""
self.sum = bar(**kwargs)
__init__.__doc__ = bar.__doc__
def bar(a, b):
"""
docstring of bar.
a: int
b: int
"""
print(a b)
我想做的是:在bar. 該類Foo使用bar. 我想避免重復代碼,即我想避免a: int在Foo. 因此,我試圖通過添加該行來“移植”(這是正確的術語嗎?)barinto的檔案字串。Foo__init__.__doc__ = bar.__doc__
這是正確的方法嗎?我在黑客嗎?ImagineFoo是 API 的一部分,而bar后臺子程式是。向用戶顯示檔案字串的正確方法是bar什么?
uj5u.com熱心網友回復:
您需要bar在Foo. 在您當前的配置中,該名稱bar在執行類主體時不存在于全域命名空間中。
您可能會考慮在檔案之間添加換行符或某種分隔符:
__init__.__doc__ = '\n' bar.__doc__
檔案很少直接從檔案字串中讀取。更好的答案是使用sphinx 之類的工具以 HTML 或 PDF 等格式生成可用檔案。而不是復制和粘貼的檔案bar成的Foo.__init__,你可以鏈接到它。這樣做的好處是您不需要重新排列全域命名空間中的物件。
流行的繪圖庫matplotlib是您的確切用例的一個很好的例子。它有許多函式,例如matplotlib.pyplot.subplots,它通過剩余的引數 ( fig_kw) 到matplotlib.pyplot.figure。查看docstring的來源,我們看到:
**fig_kw All additional keyword arguments are passed to the `.pyplot.figure` call.
反引號在 sphinx 中生成一個鏈接。您可以Foo.__init__以類似的方式撰寫 docstring :
"""
docstring of Foo.
Parameters
----------
**kwargs
Arguments passed through to `bar`.
"""
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/329791.html
下一篇:PHPOOP中的重寫方法
