How do I programmatically set the docstring?

前端 未结 6 1843
慢半拍i
慢半拍i 2020-12-01 07:21

I have a wrapper function that returns a function. Is there a way to programmatically set the docstring of the returned function? If I could write to __doc__ I\

6条回答
  •  遥遥无期
    2020-12-01 07:38

    An instancemethod gets its docstring from its __func__. Change the docstring of __func__ instead. (The __doc__ attribute of functions are are writeable.)

    >>> class Foo(object):
    ...     def bar(self):
    ...         pass
    ...
    >>> Foo.bar.__func__.__doc__ = "A super docstring"
    >>> help(Foo.bar)
    Help on method bar in module __main__:
    
    bar(self) unbound __main__.Foo method
        A super docstring
    
    >>> foo = Foo()
    >>> help(foo.bar)
    Help on method bar in module __main__:
    
    bar(self) method of __main__.Foo instance
        A super docstring
    

    From the 2.7 docs:

    User-defined methods

    A user-defined method object combines a class, a class instance (or None) and any callable object (normally a user-defined function).

    Special read-only attributes: im_self is the class instance object, im_func is the function object; im_class is the class of im_self for bound methods or the class that asked for the method for unbound methods; __doc__ is the method’s documentation (same as im_func.__doc__); __name__ is the method name (same as im_func.__name__); __module__ is the name of the module the method was defined in, or None if unavailable.

    Changed in version 2.2: im_self used to refer to the class that defined the method.

    Changed in version 2.6: For 3.0 forward-compatibility, im_func is also available as __func__, and im_self as __self__.

提交回复
热议问题