Python装饰器

作者: Solomon_Xie | 来源:发表于2019-01-13 03:07 被阅读0次

    极简样式:

    # Define a decorator
    def outter(func):
        def alternative():
            # ...Some code here...
            result = func()
            # ...Some code here...
            return result
    
        return alternative
    
    # Apply a decorator
    @outter
    def stable_method():
        pass
    

    标准样式:

    # Define a decorator
    def outter(func):
        def alternative(*args, **kargs):
            # ...Some code here...
            result = func(*args, **kargs)
            # ...Some code here...
            return result
    
        return alternative
    
    # Apply a decorator
    @outter
    def stable_method():
        pass
    

    装饰器带参数样式:

    # Define a decorator
    def outter(name):
        def inner(func):
            def alternative(*args, **kargs):
                print('I can use name={} here'.format(name))
                # ...Some code here...
                result = func(*args, **kargs)
                # ...Some code here...
            return result
    
            return alternative
        return inner
    
    # Apply a decorator
    @outter(name='Jason')
    def stable_method():
        pass
    ``
    
    
    ## 类中定义装饰器
    
    [参考:Decorator inside Python class](https://medium.com/@vadimpushtaev/decorator-inside-python-class-1e74d23107f6)

    相关文章

      网友评论

        本文标题:Python装饰器

        本文链接:https://www.haomeiwen.com/subject/nhfirqtx.html