V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
推荐学习书目
Learn Python the Hard Way
Python Sites
PyPI - Python Package Index
http://diveintopython.org/toc/index.html
Pocoo
值得关注的项目
PyPy
Celery
Jinja2
Read the Docs
gevent
pyenv
virtualenv
Stackless Python
Beautiful Soup
结巴中文分词
Green Unicorn
Sentry
Shovel
Pyflakes
pytest
Python 编程
pep8 Checker
Styles
PEP 8
Google Python Style Guide
Code Style from The Hitchhiker's Guide
jxwho
V2EX  ›  Python

关于 python 的属性__wrapped__

  •  
  •   jxwho · 2014-03-01 07:28:07 +08:00 · 3719 次点击
    这是一个创建于 3714 天前的主题,其中的信息可能已经有所发展或是发生改变。
    问个小白问题,假如写decorator的时候,调用functools里面的wraps,比如说
    def timethis(func):
    @wraps(func)
    def wrapper(*args, **kwargs):
    start = time.time()
    result = func(*args, **kwargs)
    end = time.time()
    print(func.__name__, end - start)
    return result
    return wrapper

    然后我创建时,
    @timethis
    def countdown(n):
    while n > 0:
    n--

    请问,countdown有__wrapped__这个属性吗?
    因为我看书上它是说用countdown.__wrapped__来unwrap decorator,但是我自己用的时候貌似没有这个属性,是不是要自己在第一个函数里面赋值?比如,wrapper.__wrapped__ = func 这样?
    谢谢!
    1 条回复    1970-01-01 08:00:00 +08:00
    mengzhuo
        1
    mengzhuo  
       2014-03-01 14:55:44 +08:00
    自己试试看不就知道了————_没有_

    至于unwrap,去掉decorator不就好了吗……

    :def log(func):
    ...:@functools.wraps(func)
    ...:def wrapper(*args, **kwargs):
    .......:return func(*args, **kwargs)
    ...:return wrapper

    :@log
    :def print_b(name):
    ...:"""hehe"""
    ...:print name

    In [10]: dir(print_b)
    Out[10]:
    ['__call__',
    '__class__',
    '__closure__',
    '__code__',
    '__defaults__',
    '__delattr__',
    '__dict__',
    '__doc__',
    '__format__',
    '__get__',
    '__getattribute__',
    '__globals__',
    '__hash__',
    '__init__',
    '__module__',
    '__name__',
    '__new__',
    '__reduce__',
    '__reduce_ex__',
    '__repr__',
    '__setattr__',
    '__sizeof__',
    '__str__',
    '__subclasshook__',
    'func_closure',
    'func_code',
    'func_defaults',
    'func_dict',
    'func_doc',
    'func_globals',
    'func_name']
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   817 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 28ms · UTC 20:13 · PVG 04:13 · LAX 13:13 · JFK 16:13
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.