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

Python 参数装饰器

  •  
  •   fanhaipeng0403 · 2018-11-29 15:02:41 +08:00 · 822 次点击
    这是一个创建于 1946 天前的主题,其中的信息可能已经有所发展或是发生改变。
    
    import functools
    
    
    # 第一种
    ##################################################
    def require_permission(permissions):
        def decorated(func):
            @functools.wraps(func)
            def wrapper(*args, **kwargs):
                has_permissions = permissions
                if has_permissions:
                    return func(*args, **kwargs)
                else:
                    print(403)
    
            return wrapper
    
        return decorated
    
    
    @require_permission(True)
    def foo():
        print('foo')
    
    
    @require_permission(False)
    def foo():
        print('foo')
    
    
    
    
    # 第二种
    #####################################################################
    class require_permissions(object):
        def __init__(self, permissions):
            self.permissions = permissions
    
        def __call__(self, fn):
            @functools.wraps(fn)
            def decorated(*args, **kwargs):
    
                has_permissions = self.permissions
    
                if has_permissions:
                    return fn(*args, **kwargs)
                else:
                    print(403)
    
            return decorated
    
    
    def require_permission(permission):
        return require_permissions(permission)
    
    
    @require_permission(True)
    def foo1():
        print('foo')
    
    
    if __name__ == '__main__':
        foo()
        foo1()
    
    目前尚无回复
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   1540 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 96ms · UTC 17:15 · PVG 01:15 · LAX 10:15 · JFK 13:15
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.