[英]Is there a way to generate IPython docstrings on the fly?
I like that IPython will fetch docstrings if I type foo.bar?
我喜欢如果我输入foo.bar?
,则IPython将获取文档字符串foo.bar?
However, I may sometimes build the foo.bar
method dynamically, using foo.__getattr__
. 但是,有时我可能会使用foo.__getattr__
动态地构建foo.bar
方法。 I could conceivably also generate a docstring dynamically, perhaps in a magic method like foo.__getdoc__
. 可以想象,我也可以动态生成文档字符串,也许可以使用foo.__getdoc__
这样的魔术方法。
Does IPython provide any mechanism for doing this, such that it would discover and display docstrings built on the fly? IPython是否提供任何执行此操作的机制,以便它可以发现并显示即时生成的文档字符串?
您可以设置foo.__doc__ = "my doc string"
。
That has nothing to do with IPython, IPython just reads the __doc__
attribute of an object. 这与IPython无关,IPython只是读取对象的__doc__
属性。 If you dynamically create your objects in the __getattr__
method you should just set their __doc__
attribute as well and everything will work correctly in IPython. 如果您在__getattr__
方法中动态创建对象,则应该只设置它们的__doc__
属性,并且一切都将在IPython中正常工作。
Here is an example: 这是一个例子:
class A(object):
def __init__(self, name):
self.name = name
def __repr__(self):
return 'A[%s]' % self.name
class Test(object):
def __getattr__(self, name):
a = A(name)
a.__doc__ = 'My a documentation'
return a
In [11]: t = Test()
In [12]: t.foo
A[foo]
In [13]: t.foo?
Type: A
String Form:A[foo]
Docstring: My a documentation
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.