بيثون ديكور التعامل مع المستندات
سؤال
لدي مشكلة باستخدام docstrings مع الديكور. بالنظر إلى المثال التالي:
def decorator(f):
def _decorator():
print 'decorator active'
f()
return _decorator
@decorator
def foo():
'''the magic foo function'''
print 'this is function foo'
help(foo)
الآن لا تريني المساعدة foo
كما هو متوقع ، يظهر:
Help on function _decorator in module __main__:
_decorator()
بدون الديكور ، تكون المساعدة صحيحة:
Help on function foo in module __main__:
foo()
the magic foo function
أعلم أن الوظيفة foo
يتم لفها الزخرفة ، وبالتالي فإن كائن الوظيفة ليس هو الوظيفة foo
أي أكثر من ذلك. ولكن ما هو الحل الجميل للحصول على docstring (والمساعدة) كما هو متوقع؟
المحلول
يستخدم functools.wraps()
لتحديث سمات الديكور:
from functools import wraps
def decorator(f):
@wraps(f)
def _decorator():
print 'decorator active'
f()
return _decorator
@decorator
def foo():
'''the magic foo function'''
print 'this is function foo'
help(foo)
انظر أيضا وثائق المكتبة القياسية إلى عن على functools
.
نصائح أخرى
لقد وجدت حلاً ، لكن لا أعرف ما إذا كان لطيفًا حقًا:
def decorator(f):
def _decorator():
print 'decorator active'
f()
_decorator.__name__=f.__name__
_decorator.__doc__=f.__doc__
return _decorator
الجزء مع _decorator.__name__=f.__name__
يبدو بعض البشر قليلاً ... ما رأيك؟
ألق نظرة على functools.wraps
: http://docs.python.org/library/functools.html
لا تنتمي إلى StackOverflow