Ver Mensaje Individual
  #8 (permalink)  
Antiguo 18/08/2015, 15:23
Avatar de Tropy
Tropy
 
Fecha de Ingreso: diciembre-2013
Mensajes: 62
Antigüedad: 10 años, 5 meses
Puntos: 1
Respuesta: [Python] Retornar valores en funciones de orden superior

Utilizo python 2.7.6:

Código:
Python 2.7.6 (default, Mar 22 2014, 22:59:56) 
[GCC 4.8.2] on linux2
Type "help", "copyright", "credits" or "license" for more information.
He probado tu opción pero me da otro error:

Código Python:
Ver original
  1. def seleccion(operacion):
  2.         def suma(n, m):
  3.             return n + m
  4.          
  5.         def multiplicacion(n, m):
  6.             return n * m
  7.        
  8.         if operacion=='multi':
  9.             return multiplicacion(5,2)
  10.      
  11. fGuardada = seleccion("multi")
  12. print fGuardada

Pero me da este error:

Código:
File "de.py", line 2
    def seleccion(operacion):
    ^
IndentationError: unexpected indent
Luego intenté simplificarlo para haber si daba con el error:

Código Python:
Ver original
  1. def seleccion(operacion):
  2.     def suma(n, m):
  3.         return n + m
  4.  
  5.     if operacion == 'suma':
  6.         return suma
  7.  
  8. fGuardada = seleccion('suma')
  9.  
  10. print fGuardada(3, 4)

Pero me da este error:

Código:
Traceback (most recent call last):
  File "de.py", line 11, in <module>
    print fGuardada(3, 4)
TypeError: 'NoneType' object is not callable
También probé con darle un valor al return suma y me devuelve un resultado de: None

Gracias por sus respuestas.
Y disculpen por las molestias ocacionadas.

Saludos.

---------------------------------------------------------------------------------------------------------------------------------------------------

EDIT: Gracias por la ayuda, ya parece funcionar correctamente.

Código Python:
Ver original
  1. #Funciones de orden superior
  2. def seleccion(operacion):
  3.     def suma(n, m):
  4.         return n + m
  5.  
  6.     def multiplicacion(n, m):
  7.         return n * m
  8.  
  9.     if operacion == 'suma':
  10.         return suma
  11.     elif operacion == 'multi':
  12.         return multiplicacion
  13.  
  14. fGuardada = seleccion('suma')
  15. print fGuardada(10, 40)

Saludos.

Última edición por Tropy; 18/08/2015 a las 18:15