我必须定制__getattr__来调用另一个函数来读取。
除了帮助(object.attr)不起作用外,这一点很好。这段代码是在一个交互式环境中使用的,因此help()对我们很重要。
是否有更好的设计来实现相同的功能,但是使用help()可以很好地工作。

最佳答案

用于“帮助”的文本实际上是对象的“__doc__”属性。问题是,根据您拥有的对象,不能简单地在其上设置__doc__属性。
如果您需要的是“help(object.attr)”来工作(而不是help(object)向您显示所有可能的属性),那么这就简单了一点——您应该只让舒尔知道,无论返回什么__getattr__都有一个正确设置的docstring。
因为“它不起作用”,我猜您返回的是一些函数调用的内部结果,如下面这段代码:

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

如果您只是返回函数“foo”本身,而不调用它,那么它将正常显示。
可以做的是将返回值包装在__getattr__中,作为动态创建的类的一个对象,该类包含一个适当的docstring-因此,尝试使用如下方法:
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__返回的内容。

08-25 20:31
查看更多