python - How can I pass a variable in a decorator to function's argument in a decorated function? -
i in progress learn python. points me correct way.
i'd below:
def decorate(function): def wrap_function(*args, **kwargs): str = 'hello!' # want return function(*args, **kwargs) return wrap_function @decorate def print_message(): # i'd pass 'str' mentioned above # functions' argument below: print(str) # 'str' same above
any idea? in advance.
you can't pass own name, can add keywords.
def decorate(function): def wrap_function(*args, **kwargs): kwargs['str'] = 'hello!' return function(*args, **kwargs) return wrap_function @decorate def print_message(*args, **kwargs): print(kwargs['str'])
alternatively can name own argument:
def decorate(function): def wrap_function(*args, **kwargs): str = 'hello!' return function(str, *args, **kwargs) return wrap_function @decorate def print_message(str, *args, **kwargs): print(str)
class method:
def decorate(function): def wrap_function(*args, **kwargs): str = 'hello!' args.insert(1, str) return function(*args, **kwargs) return wrap_function class printer: @decorate def print_message(self, str, *args, **kwargs): print(str)
Comments
Post a Comment