Decorator in python - explanation needed -
Decorator in python - explanation needed -
i new python , cant understand decorators concept. trying implement 2 decorators, one, nonnegative assumes arbitrarily long list of integer arguments , throws exception if less 0, , another, allcaps, assumes arbitrarily long list of string arguments, , capitalizes them. then, write simple function test each, wrap it, , demonstrate each decorator works.
i have started , have come point.
#!/usr/local/bin/python2.7 def nonnegative(inputs): in inputs: if i<0: raise exception def allcaps(inputs2): in inputs2: = i.upper() print def inputs def inputs2(): inputfile = open ("input.txt") sentence = inputfile.readlines() words = (sentence[0].split()) homecoming words nonnegative(inputs)
i grateful if can explain me concept of decorators. tried understand couldn't.
think of decorator function wraps function.
in math might have function f(x)
. if wrap decorator g
have g(f(x))
.
in python representation is
@function_g def function_f(): pass
here's example:
def entryexit(f): def new_f(): print "entering", f.__name__ f() print "exited", f.__name__ homecoming new_f @entryexit def func1(): print "inside func1()"
you see define function extryexit
returns wrapped function (and hence takes function input). wraps function within of new_f
.
by wrapping function decorator, func1
transforms from
def func1(): print "inside func1()"
to
def func1(f): print "entering", f.__name__ print "inside func1()" print "exited", f.__name__
you can write class define decorator, function decorators less verbose in opinion.
you can read more decorators this first-class intro here.
python decorator
Comments
Post a Comment