__doc__ 是 None 方法但不是函数

__doc__ is None with method but not with function

我必须修饰一些 python 方法和函数。不幸的是,如果函数是一个方法,则获取原始函数的文档字符串的 doc 属性不起作用。

To avoid confusion here a remenber:
a function is series of instructions (e.g.def function(arg))
a method is function bind to a class (e.g.def methog(self, arg))

这是正常行为还是错误?

class GruiMethod:
    def __init__(self, callable_):
        self._instance = None
        self.real_callable = callable_

    def __get__(self, instance, owner):
        # We save the instance of the object from the method class. In case the function is a method
        self._instance = instance
        return self.__call__

    def __call__(self, *args, **kwargs):
        # Invoked on every call of any decorated method
        if self._instance:
            return self.real_callable(self._instance, *args, **kwargs)
        else:
            return self.real_callable(*args, **kwargs)

    @property
    def __doc__(self):
        return self.real_callable.__doc__

    # ...

def my_decorator(func):
    t = GruiMethod(func)
    print("Test", t.__doc__) # It actually print the rigth doc
    return t


class Foo:
    @my_decorator
    def bar(self, message):
        """This method return a welcome message"""
        return "Hello %s: %s" % (self._people, message)


@my_decorator
def my_function(message):
    """This function return a welcome message"""
    return "::%s::" % message


class TestDecorator(unittest.TestCase):
    def test_doc_attr(self):
        self.assertEqual("This function return a welcome message", my_function.__doc__) # Works
        self.assertEqual("This is a simple class to run unit test", Foo.__doc__) # Works
        self.assertEqual("This method return a welcome message", Foo().bar.__doc__) # Fail __doc__ is None

我发现了错误。其实很明显... 返回实例本身而不是 __call__ 方法可以解决问题。我不知道为什么装饰器绑定到方法时行为会有所不同,但如果有人有解释,欢迎发表评论

def __get__(self, instance, owner):
    self._instance = instance
    self._owner = owner
    return self