Perfil
>
Publicaciones de Juan
Juan Nogales

Juan Nogales

writecode4

Buenos Aires, Buenos Aires C.F.

Juan Nogales

hace 2 años

How to use decorators Python

oR
DECORATORS

Intermediate

 

@DECORATORS

Also called metaprogramming because
one part of a program tries to modify
(elgle](aT-Tgt oTela ol Md al=N olfele (eo laa No Vigigle]
compilation.

#lLet's review functions

def un(greeting): . LRT
print(greeting) —_—

functions can be passed as ar-
guments to avother function.
Those functions that take
other functions as arguments
are also called higher-order
Saal

un("Hello")

deux un .
deux ("Hello")

output

Hello
Hello

follow @writecode4

 

@DECORATORS

#An example of higher-order-functions

def frst(a): CIT Rai
PE

define a higher-order
def snd_hghr (func, a): aT
result = func(a) —
result
mvoke and assign a

final = snd_hghr(frst,3) NER Ral

print(final) =.

output

9

follow @writecode4

 

@DECORATORS

#Also, functions can return other functions

def frst(a): CTT RIT ti
def frst_square(): nesting another func-
a aC

print (frst_square)

frst(4) ) )
“ wvoke the first one

output

16

follow @writecode4

 

@DECORATORS

#lLet’s create a decorator

A RT i
def frst(func): _ Ea
vest avother
fuvction

%

def frst_square():
print (”Decorator”)
pS Q)
frst_square
ANT Ae
[15 VA [-Y-1 of @ J i
print ("Main")
my_decor = frst(my_decor)
my_decor()

output

Decorator
Main

follow @writecode4

 

@DECORATORS

#Use the decorator syntax

defin Sn )
def frst(func): _ me a function

def frst_square(): nesting another

FT aly
print (”Decorator”) iar
frst_square
Gila using a decorator syntax

Ed rE =
IS TRAGER UI)

ISR ERTZES a REV 712 STRAT VT
to implement decorators.

output

Decorator
Main

follow @writecode4

 

@DECORATORS

#Use multiple Decorators

def frst(func):
def frst_square(*args, **kwargs): \
print (”’Decorator”)

func()

i143 A a
frst_square LRP

def scnd(func):
def frst_square(*args, Rwargs): \
print (”2nd Decorator”)
func()

frst_square define other function

@frst .

@scnd

def my_decor():
print("Main")

using multiple decorators

output
Decorator

2nd Decorator
Main

follow @writecode4

#pythondeveloper #python

0 me gusta · 0 comentarios

Ciencia y Tecnología

Juan Nogales

hace 2 años

Trust

= or Re

> Believe not in a friend, neither
put your trust in a prince:
beware of her that sleepeth by
thee, and open not thy mouth.
® For the son dishonors the
father, the daughter rises up
against the mother, the daugh-
ter-in-law against her moth-
er-in-law, and a man's enemies
are those of his own household.

0 me gusta · 0 comentarios

Lecciones de Vida

¿Quieres gestionar tu propio grupo?

orange logo