Passing a parameter to the decorator in python

前端 未结 2 1638
小蘑菇
小蘑菇 2021-01-12 13:40

Why is this decorator with a parameter not working?

def decAny( f0 ):
    def wrapper( s0 ):
        return \"<%s> %s \" % ( any, f0(), any          


        
2条回答
  •  爱一瞬间的悲伤
    2021-01-12 14:32

    There is a good sample from "Mark Lutz - Learning Python" book:

    def timer(label=''):
        def decorator(func):
            def onCall(*args):   # Multilevel state retention:
                ...              # args passed to function
                func(*args)      # func retained in enclosing scope
                print(label, ... # label retained in enclosing scope
            return onCall
        return decorator         # Returns the actual decorator
    
    @timer('==>')                # Like listcomp = timer('==>')(listcomp)
    def listcomp(N): ...         # listcomp is rebound to new onCall
    
    listcomp(...)                # Really calls onCall
    

提交回复
热议问题