+ 1
How to use decorators on functions with arguments?
def decor(func): def wrap(): print("============") func() print("============") return wrap @decor def print_text(x): print("Hello {0} !".format(x) ) print_text(72); Modify this and make it run. Thanks.
5 Respuestas
+ 2
def decor(func):
def wrap(*args, **kwargs):
print("============")
func(*args, **kwargs)
print("============")
return wrap
@decor
def print_text(x):
print("Hello {0} !".format(x) )
print_text(72);
+ 2
You should use *args, **kwargs generally, if you want your decorator to work with all possible functions. Suppose you have to decorate a function with 2 or even unknown number of arguments, like print. https://docs.python.org/3/library/functions.html?highlight=print#print
It has unknown number of arguments and several default arguments like 'sep', 'end' and so on:
>>> print(1,2)
1 2
>>> print(1,2,3)
1 2 3
>>> print(1,2,3, sep='-')
1-2-3
>>> print(1,2,3, sep='-', end='!')
1-2-3!
* in *args, **kwargs means unpack operation. For instance:
>>> a = (1,2,3)
>>> print(a)
(1, 2, 3)
>>> print(*a) #the same as print(1,2,3)
1 2 3
>>> d = {'sep':'-', 'end':'!'}
>>> print(d)
{'end': '!', 'sep': '-'}
>>> print(*d)
end sep
>>> print(*a, **d) #the same as print(1,2,3, sep='-', end='!')
1-2-3!
args is the python name for a tuple of positional argument values passed to your function, while kwargs is the dictionary of keyword argument values:
>>> def decor(func):
def wrap(*args, **kwargs):
print('args:', args)
print('kwargs:', kwargs)
func(*args, **kwargs)
return wrap
>>> @decor
def printsum(a,b,c,d=0):
print(a+b+c+d)
>>> printsum(1,2,c=3,d=4)
args: (1, 2)
kwargs: {'c': 3, 'd': 4}
10
https://pythontips.com/2013/08/04/args-and-kwargs-in-python-explained/
+ 1
This also works. Can anyone explain why?
How argument in print_text is carried in wrap function inside decorator?
#--------------------------------------
#--------------------------------------
def decor(func):
def wrap(y):
print("============")
func(y)
print("============")
return wrap
@decor
def print_text(x):
print("Hello {0} !".format(x) )
print_text(72);
#--------------------------------------
#--------------------------------------
0
These *args, **kwargs. Can you explain them little bit. Are these given in the SoloLearn python? Right now i am in the Object Oriented module
and i haven't seen them yet.
0
Here is an example:
https://code.sololearn.com/cD09ijlIS6Ev/?ref=app