如何强制帮助使用被覆盖的__doc__

时间:2017-01-07 15:22:20

标签: python python-3.x docstring

我们假设我定义了一个简单的类Foo

class Foo(object):
    """This is Foo"""
    def __init__(self, label):
        self.__doc__ = "This is {} Foo".format(label)

    def __call(self, *args):
        ... # Some behavior which depends on the constructor arguments.

我在IPython中看到__doc__拾取了对象?

In [1]: %doctest_mode
Exception reporting mode: Plain
Doctest mode is: ON
>>> some = Foo("some")
>>> ?some
Type:            Foo
String form:     <__main__.Foo object at 0x7f01620a49b0>
Docstring:       This is some Foo
Class docstring: This is Foo

但被help忽略:

>>> help(some)

Help on Foo in module __main__ object:

class Foo(builtins.object)
 |  This is Foo
 |  
 |  Methods defined here:
 |  
 |  __init__(self, label)
 |      Initialize self.  See help(type(self)) for accurate signature.
 |  
 |  ----------------------------------------------------------------------
 |  Data descriptors defined here:
 |  
 |  __dict__
 |      dictionary for instance variables (if defined)
 |  
 |  __weakref__
 |      list of weak references to the object (if defined)
(END)

是否可以在不修改help的情况下影响Class docstring行为?我希望在处理实例时忽略Class docstring

2 个答案:

答案 0 :(得分:1)

强制help功能需要根据我的理解更改其实现。创建一个临时在类上重新分配__doc__的辅助函数要容易得多:

def my_help(obj):
    if not isinstance(obj, type):  # instances
        old_doc, type(obj).__doc__ = type(obj).__doc__, obj.__doc__
        help(type(obj))
        type(obj).__doc__ = old_doc
    else:
        help(obj)

根据我的理解,这产生了让实例的文档字符串替换类的效果:

my_help(Foo('foo'))
Help on class Foo in module __main__:

class Foo(builtins.object)
 |  This is foo Foo
 |  
 |  Methods defined here:
 |  
 |  __init__(self, label)
 |      Initialize self.  See help(type(self)) for accurate signature.
 |  
 #  .. snipped ..

我真的不喜欢这个,并且知道你必须在那里执行try-except的类,这些类不允许你像这样设置属性。简而言之,可行而且笨重。

答案 1 :(得分:1)

第一:我不推荐它!如果根据参数认真改变逻辑,那么最好使用工厂函数和几个不同的(子)类。

说完之后:这是可能的。一种方法是使用动态类型和子类。但是,您需要使用new_list = range (0,10) for element in new_list[5:9]: print "numbers are", element 代替__new__

__init__