File tree 1 file changed +62
-0
lines changed
Roadmap/24 - DECORADORES/python
1 file changed +62
-0
lines changed Original file line number Diff line number Diff line change
1
+ # funcion decoradora que recibe otra funcion como parametro
2
+ def decorador (funcion ):
3
+ # crear otra funcion
4
+ def f ():
5
+ print ('Antes de ejecutar la función' ) # hacer algo antes
6
+ funcion () # ejecutar la funcion recibida como argumento
7
+ print ('Después de ejecutar la función' ) # hacer algo después
8
+
9
+ # retornar funcion f
10
+ # f = funcion decoradora + funcion recibida como argumento
11
+ return f
12
+
13
+ # decorar la funcion saludo
14
+ @decorador
15
+ def saludo ():
16
+ print ('Hola!' )
17
+
18
+ # ejecutar la funcion con el decorador aplicado
19
+ saludo ()
20
+
21
+ print ("\n " )
22
+
23
+ # ---- DIFICULTAD EXTRA ----
24
+
25
+ from random import choice , randint
26
+
27
+ def contador (funcion ):
28
+ # *args: argumentos posicionales variables
29
+ # **kwargs: diccionario de argumentos variables
30
+ def f (* args , ** kwargs ):
31
+ f .contador += 1
32
+ return funcion (* args , ** kwargs )
33
+
34
+ # a la funcion le añado una propiedad contador
35
+ f .contador = 0
36
+ return f
37
+
38
+ @contador
39
+ def sumatoria (m , M ):
40
+ return sum (range (m , M ))
41
+
42
+ @contador
43
+ def factorial (n ):
44
+ if n == 0 :
45
+ return 1
46
+ return n * factorial (n - 1 )
47
+
48
+ for _ in range (10 ):
49
+ bin_choice = choice ([0 , 1 ])
50
+ if bin_choice :
51
+ m = randint (- 10 , 10 )
52
+ M = abs (m ) * 2
53
+ print (f"Sumatoria de { m } a { M } : { sumatoria (m , M )} " )
54
+ else :
55
+ n = randint (0 , 10 )
56
+ print (f"Factorial de { n } : { factorial (n )} " )
57
+
58
+ print ()
59
+ print (f"Cantidad de sumas: { sumatoria .contador } " )
60
+
61
+ # el factorial se ejecuta mas veces porque es recursivo
62
+ print (f"Cantidad de factoriales: { factorial .contador } " )
You can’t perform that action at this time.
0 commit comments