推荐学习书目
› 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 · Mar 1, 2014 · 4655 views
    This topic created in 4592 days ago, the information mentioned may be changed or developed.
    问个小白问题,假如写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 replies  •  1970-01-01 08:00:00 +08:00
    mengzhuo
        1
    mengzhuo  
       Mar 1, 2014
    自己试试看不就知道了————_没有_

    至于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']
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Privacy   ·   Solana   ·   841 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 24ms · UTC 21:16 · PVG 05:16 · LAX 14:16 · JFK 17:16
    ♥ Do have faith in what you're doing.