doc为__getattr__定义了属性

For*_*ang 5 python pydoc getattr

我必须自定义__getattr__调用另一个函数来读取.

除了help(object.attr)不起作用之外,这种方法很有效.此代码用于交互式环境,因此help()对我们很重要.

是否有更好的设计来实现相同的功能,但help()运行良好.

jsb*_*eno 1

用于“帮助”的文本确实是__doc__对象的“”属性。问题是,根据您拥有的对象,您不能简单地设置__doc__其属性。

\n\n

如果您需要的是“ help(object.attr)”来工作(而不是向help(object)您显示所有可能的属性),那么会更容易一些 - 您应该只确定任何__getattr__返回的内容都具有正确设置的文档字符串。

\n\n

由于“它不起作用”,我猜测您正在返回某些函数调用的内部结果,如以下代码片段所示:

\n\n
def __getattr__(self, attr):\n    if attr == "foo":\n        #function "foo" returns an integer\n        return foo()\n    ...\n
Run Code Online (Sandbox Code Playgroud)\n\n

如果您只是返回函数“foo”本身,而不调用它,则 it\xc5\x9b 文档字符串将正常显示。

\n\n

可以做的是将返回值包装为__getattr__动态创建的类的对象,其中包含正确的文档字符串 - 因此,尝试使用如下内容:

\n\n
def __getattr__(self, attr):\n    if attr == "foo":\n        #function "foo" returns an (whatever object)\n        result = foo()\n        res_type = type(result)\n        wrapper_dict = res_type.__dict__.copy()\n        wrapper_dict["__doc__"] = foo.__doc__ #(or "<desired documentation for this attribute>")\n        new_type = type(res_type.__name__, (res_type,), wrapper_dict)\n        # I will leave it as an "exercise for the reader" if the \n        # constructor of the returned object can\'t take an object\n        # of the same instance (python native data types, like int, float, list, can)\n        new_result = new_type(result)\n    elif ...: \n        ...\n    return new_result\n
Run Code Online (Sandbox Code Playgroud)\n\n

这应该有效 - 除非我一开始就弄错了 hel 不工作的动机 - 如果是这种情况,请举一些您从 . 返回的示例__getattr__

\n