0

我在玩文档字符串,最后得到了这段代码:

import inspect

class InheritedDoc(object):
    """ Decorator to find docstrings from parent classes of
        the method class.
        Decorator are interpreted on the import and not
        on the call, so the inherated docstrings will be
        read when we call help.

        @type mroOrder: bool
        @param mroOrder: follow the order of the
            method resolution order (True) or reserse it (False).
            Default: True.

        @Note: if this doc is seen in the code, instead of the
            docstring of a superClass, that must means the "()"
            are missing on the call of InheritedDoc:
                @InheritedDoc -> @InheritedDoc()
    """
    __empty_doc = 'No Doc found in parent classes.\n'
    __empty_doc += 'DocString needs to be set.'

    def __init__(self, mroOrder=True):
        """ Constructor
        """
        self.__mro_order = mroOrder

    def __call__(self, method):
        """ If there are decorator arguments, __call__()
            is only called once, as part of the decoration
            process!
            You can only give it a single argument,
            which is the function object.
        """
        # Generated only if help() were used.
        # Listing of super classes of the method class.
        #
        parent_classes = [
            element for name, element \
               in method.func_globals.items() \
                  if inspect.isclass(element)
        ]

        # We don't want to inheritate from the decorator itself.
        #
        parent_classes.remove(self.__class__)

        # Do we follow the order of the MRO or do we reverse it.
        #
        if not self.__mro_order:
            parent_classes = reversed(parent_classes)

        name = method.__name__

        doc = ''

        for parent_class in parent_classes:

            # Testing if the class define the method
            #
            if hasattr(parent_class, name):
                # Getting the method to find in it the doc.
                #
                class_method = eval('parent_class.%s' % name)
                doc = class_method.__doc__

                # We want to define the doc only if the method
                # got a doc set.
                #
                if doc:
                    # The doc is defined and we don't want
                    # to keep on defining it again and again. 
                    #
                    break

        # We may end up here without any docstring if none were 
        # actually set in parent classes.
        #
        method.__doc__ = doc or self.__empty_doc

        return method
4

0 回答 0