+ 2

Python decorators

def check(func): def check2(a,b,c): if type(a)==int and type(b)==int: return func(a,b) else: raise "Data type wrong for input" return check2 @check def sum(x,y): return x + y print(sum(4,'l')) Guys above code will return me error that check2 takes 3 args but 2 are given. Where we are passing the value in check2 ? . If I keep 2 args in check2 then it will work.I am new to decorators. So it will helpful if someone tell me the code flow.How calling is done at each step. Thanks in advance!!

22nd Nov 2018, 2:48 PM
Biru Kathayet
Biru Kathayet - avatar
2 ответов
+ 6
Biru Kathayet i know decorater is bit complex.i will explain how this code works. You define check function here check is the name of the function which will decorate other function.then again you define check2 inner function and it take 3 arguments.but here remember that the number of the arguments in check2 should be equal to the number of the arguments in a function which you want to decorate.means no.argument == no. of argument of sum otherwise you got error. And then your code logic. In last line you are returning check2 function basically you are returning the decorating version of sum function. Remember that check2 which is the inner function of check is the 2nd name of the sum function you can say. I recommend you should read Dan bader python tricks book which is best and decorater make simple in this book.
22nd Nov 2018, 4:26 PM
Maninder $ingh
Maninder $ingh - avatar
0
Thank you Maninder for reply.I would definately go through the mentioned book.
22nd Nov 2018, 4:54 PM
Biru Kathayet
Biru Kathayet - avatar