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
su27k2003
V2EX  ›  Python

有关 Python 修饰函数的问题

  •  
  •   su27k2003 · 2018-07-02 18:37:25 +08:00 · 1497 次点击
    这是一个创建于 2115 天前的主题,其中的信息可能已经有所发展或是发生改变。

    最近在研究 python 修饰函数,虚心请教如下问题。废话不说,先上代码:

    import time
    from datetime import datetime
    from datetime import timedelta
    
    def time_func(time_interval, default=None):
        def decorator(func):
            func.__last_run = datetime.min
            def guard(*args, **kwargs):
                now = datetime.now()
                if now - func.__last_run >= time_interval:
                    func.__last_run = now
                    return func(*args, **kwargs)
                elif default is not None:
                    return default(*args, **kwargs)
            return guard
        return decorator
    
    
    if __name__ == "__main__":
        
        @time_func(timedelta(seconds=4),None)
        def add():
            print('test')
    
        add()
        add()
    

    执行结果: 只显示一个'test'

    问题: 这个代码实现了在规定时间内( time_interval )限制了函数 add ()的运行次数,只让它运行一次,其余忽略。 请问此代码中为何在执行第二遍 add()的时候跳过了开头的 func.__last_run = datetime.min 而直接进入 guard 中的代码?该怎样理它的解运作原理? Python 新手,十分感谢!

    baichi
        2
    baichi  
       2018-07-03 03:21:14 +08:00   ❤️ 1
    billgreen1
        3
    billgreen1  
       2018-07-03 09:49:25 +08:00   ❤️ 1
    这么说吧,你不要调用 add(), 直接在 ipython 里面输入 add, 你会看到 add 其实不是 add 了,而是
    <function __main__.time_func.<locals>.decorator.<locals>.guard(*args, **kwargs)>,
    其实是 guard,但是这个 guard 绑定了一个它的外部变量,__last_run
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   1094 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 25ms · UTC 18:37 · PVG 02:37 · LAX 11:37 · JFK 14:37
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.