6

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

这很好用,除了 help(object.attr) 不起作用。这段代码是在交互式环境中使用的,所以 help() 对我们来说变得很重要。

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

4

2 回答 2

1

您可以将属性转换为属性。该属性将自动使用 getter 方法的文档字符串作为自己的。或者,您可以将doc参数提供给property().

于 2012-02-03T16:13:18.833 回答
1

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

如果您需要的是“ help(object.attr)”来工作(而不是help(object)显示所有可能的属性)它会更容易一些 - 您应该只知道无论__getattr__返回什么都包含正确设置的文档字符串。

因为“它不工作”我猜你正在返回一些函数调用的内部结果,就像在这个片段中一样:

def __getattr__(self, attr):
    if attr == "foo":
        #function "foo" returns an integer
        return foo()
    ...

如果您只是简单地返回函数“foo”本身,而不调用它,它的文档字符串将正常显示。

可以做的是将返回值包装__getattr__为动态创建的类的对象,该类包含正确的文档字符串 - 所以,尝试使用这样的东西:

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

这应该有效 - 除非我弄错了 hel 不工作的动机 - 如果是这种情况,请举例说明你从什么返回__getattr__

于 2012-02-04T02:29:21.243 回答