[英]__doc__ is None with method but not with function
我必須裝飾一些 python 方法和函數。 不幸的是,如果 function 是一種方法,則獲取原始 function 的文檔字符串的doc屬性不起作用。
為避免混淆,請記住:
a function 是一系列指令(例如def function(arg)
)
一種方法是 function 綁定到 class (例如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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.