__getattr__定义的属性的文档 [英] doc for __getattr__ defined attributes

查看:77
本文介绍了__getattr__定义的属性的文档的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have to customize __getattr__ to call another function to read.

这很好用,除了help(object.attr)不起作用.这段代码用于交互式环境,因此help()对我们来说很重要.

This works well except the help(object.attr) does not work. This code is used in an interactive environment, so the help() becomes important to us.

是否有更好的设计来实现相同的功能,但help()可以正常工作.

Is there a better design to achieve same features but with help() working well.

推荐答案

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

The text that is used for "help" is indeed the "__doc__" attribute of an object. The matter is that depending on the object you have, you can't simply set the __doc__ attribute on it.

如果您需要的是"help(object.attr)"来工作(而不是help(object)显示所有可能的属性),这会容易一些-您应该确保__getattr__返回的内容必须正确设置文档字符串.

If what you need is "help(object.attr)" to work (and not that help(object) shows you all possible attributes) it is a bit easier - you should only get shure that whatever __getattr__ returns do hae a properly set docstring.

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

SInce "it is not working" I'd guess you are returning the internal results of some function call, like in this snippet:

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

如果仅返回函数"foo"本身而不调用它,它的文档字符串将正常显示.

If you simply would return the function "foo" itself, without calling it, itś docstring would be displayed normally.

可以做的是将返回值包装在__getattr__中,作为动态创建的类的对象,该类包含适当的文档字符串-因此,请尝试使用诸如此类的东西:

What can be done is to wrap the return value in __getattr__ as an object of a dynamically created class wich contains a proper docstring - so, try using somethong like this:

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__返回的内容.

This should work - unless I got wrong the motive why hel is not working in the first place - if that is the case, please give some example of what you are returning from __getattr__.

这篇关于__getattr__定义的属性的文档的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆