[Tutor] Function decorators
Manprit Singh
manpritsinghece at gmail.com
Tue Dec 1 21:33:41 EST 2020
Dear sir ,
Below written is the code for the question given by you in your last mail .
For example can you, without considering decorators,
define a function that returns a new function that
will calculate a given power?
>>> def exponent_builder2(x):
def ypowx(y):
return y**x
return ypowx
>>> sqr = exponent_builder2(2)
>>> sqr(7) # will give 47
49
cube = exponent_builder2(3)
>>> cube(3) #will give 27
27
This definition can be written in more easy way with lambda expression as
below:
>>> def exponent_builder(x):
return lambda y: y**x
So,what is the next exercise for me to understand the function
decorators? the code written above by me is correct ? kindly let me know
Regards
Manprit Singh
On Mon, Nov 30, 2020 at 10:47 PM Alan Gauld via Tutor <tutor at python.org>
wrote:
> On 30/11/2020 14:39, Manprit Singh wrote:
> > I tried to understand the concept of function decorators from various
> > sources but couldn't .
>
> They are a fairly advanced concept that is rarely
> used (as in creating decorators) in every day programming.
> Decorators are easy enough to use once created even if you
> don't understand what they do under the covers.
> But creating a decorator is slightly more complex.
>
> In essence a decorator is a function that returns
> a function and then gets called through a bit of
> Python syntactical magic - the @prefix.
>
> Before understanding decorators do you understand
> the concept of functions as objects? Are you
> comfortable with lambdas? Lambdas aren't needed
> for decorators but if you understand what lambdas
> do you will find it a shorter step to decorators.
>
> For example can you, without considering decorators,
> define a function that returns a new function that
> will calculate a given power?
>
> def exponent_builder(n)
> def f(....
> return f
>
> square = exponent_builder(2)
> print(square(7) ) -> prints 49
>
> triple = exponent_builder(3)
> print( triple(3)) -> prints 27
>
> If you can write exponent_builder() you are well
> on the way to writing a decorator.
>
> > I am sorry if I said something wrong.
>
> No, it's a reasonable question. You will need to
> be more specific now in any follow-up.
>
>
> --
> Alan G
> Author of the Learn to Program web site
> http://www.alan-g.me.uk/
> http://www.amazon.com/author/alan_gauld
> Follow my photo-blog on Flickr at:
> http://www.flickr.com/photos/alangauldphotos
>
>
> _______________________________________________
> Tutor maillist - Tutor at python.org
> To unsubscribe or change subscription options:
> https://mail.python.org/mailman/listinfo/tutor
>
More information about the Tutor
mailing list