-
Notifications
You must be signed in to change notification settings - Fork 4.4k
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Merge pull request #7800 from idiegorojas/main
#9 - Python
- Loading branch information
Showing
2 changed files
with
245 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,126 @@ | ||
# 09 - Herencias | ||
|
||
# Clase padre | ||
class Animal: | ||
|
||
def __init__(self, nombre, edad): | ||
self.nombre = nombre | ||
self.edad = edad | ||
|
||
def sonido(self): | ||
print('Algun sonido') | ||
|
||
def presentarse(self): | ||
print(f'Hola, soy {self.nombre}, y tengo {self.edad} años.') | ||
|
||
# Clase Hija | ||
class Perro(Animal): | ||
|
||
def __init__(self, nombre, edad, raza): | ||
# Llamamos al constructor de la clase padre | ||
super().__init__(nombre, edad) | ||
self.raza = raza | ||
|
||
# Sobrescribimos el metodo sonido | ||
def sonido(self): | ||
print('¡Guau, guau!') | ||
|
||
# Agregamos un metodo especifico del Perrro | ||
def perseguir_cola(self): | ||
print(f'{self.nombre} esta persiguiendo su cola') | ||
|
||
class Gato(Animal): | ||
|
||
def __init__(self, nombre, edad, color): | ||
# Llamamos al constructor de la clase padre | ||
super().__init__(nombre, edad) | ||
self.color = color | ||
|
||
# Sobrescribimos el metodo sonido | ||
def sonido(self): | ||
print('Miau') | ||
|
||
# Agregamos un metodo especifico del Gato | ||
def dormir(self): | ||
print(f'{self.nombre} esta durmiendo.') | ||
|
||
|
||
mi_perro = Perro('Max', 3, 'Pug') | ||
mi_perro.presentarse() | ||
mi_perro.sonido() | ||
mi_perro.perseguir_cola() | ||
|
||
mi_gato = Gato('Luna', 2, 'Negro') | ||
mi_gato.presentarse() | ||
mi_gato.sonido() | ||
mi_gato.dormir() | ||
|
||
|
||
# Extra | ||
|
||
class Empleado: | ||
|
||
def __init__(self, id, nombre, cargo): | ||
self.id = id | ||
self.nombre = nombre | ||
self.cargo = cargo | ||
self.empleados = [] | ||
|
||
def presentarse(self): | ||
print(f'Hola, mi nombre es {self.nombre} y mi cargo es {self.cargo}') | ||
|
||
def agregar_empleado(self, empleados): | ||
self.empleados.append(empleados) | ||
|
||
def listar_empleados(self): | ||
if len(self.empleados) >= 1: | ||
print(f'{self.nombre} tiene a cargo {len(self.empleados)} empleados.') | ||
else: | ||
print(f'{self.nombre} no tiene empleados a cargo.') | ||
|
||
|
||
class Gerente(Empleado): | ||
|
||
def __init__(self, id, nombre, cargo): | ||
super().__init__(id, nombre, cargo) | ||
|
||
def planifica(self): | ||
print(f'Como {self.cargo}, estoy planificando los objetivos del proximo año') | ||
|
||
|
||
class GerenteProyecto(Empleado): | ||
|
||
def __init__(self, id, nombre, cargo): | ||
super().__init__(id, nombre, cargo) | ||
|
||
def ejecuta(self): | ||
print(f'Como {self.cargo}, estoy ejecutando los objetivos de este año') | ||
|
||
|
||
class Programador(Empleado): | ||
|
||
def __init__(self, id, nombre, cargo): | ||
super().__init__(id, nombre, cargo) | ||
|
||
def desarrolla(self): | ||
print(f'Como {self.cargo}, estoy desarrollando un programa para alcanzar los objetivos.') | ||
|
||
|
||
gerente_1 = Gerente(1, 'Jorge', 'Gerente') | ||
gerente_1.presentarse() | ||
gerente_1.planifica() | ||
|
||
gerente_proyecto_1 = GerenteProyecto(2, 'Felipe', 'Gerente de Proyectos') | ||
gerente_proyecto_1.presentarse() | ||
gerente_proyecto_1.ejecuta() | ||
|
||
programador_1 = Programador(3, 'Raul', 'Programador') | ||
programador_1.presentarse() | ||
programador_1.desarrolla() | ||
|
||
gerente_1.agregar_empleado(gerente_proyecto_1) | ||
gerente_proyecto_1.agregar_empleado(programador_1) | ||
|
||
gerente_1.listar_empleados() | ||
gerente_proyecto_1.listar_empleados() | ||
programador_1.listar_empleados() |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,119 @@ | ||
# Excepciones | ||
|
||
# Tipos de excepciones | ||
|
||
# ZeroDivisionError: Ocurre cuando se intenta dividir entre cero. | ||
# TypeError: Ocurre cuando se realiza una operación con tipos de datos incompatibles. | ||
# ValueError: Ocurre cuando una función recibe un argumento con el tipo correcto pero un valor inapropiado. | ||
# FileNotFoundError: Ocurre cuando se intenta abrir un archivo que no existe. | ||
# IndexError: Ocurre cuando se intenta acceder a un índice fuera de rango en una lista. | ||
# KeyError: Ocurre cuando se intenta acceder a una clave que no existe en un diccionario. | ||
|
||
# Estructura basica | ||
try: | ||
# Dividir por cero genera la excepcion 'ZeroDivisionError' | ||
resultado = 10 / 0 | ||
except ZeroDivisionError: | ||
# Codigo que se ejecuta si se da la excepcion 'ZeroDivisionError' | ||
print('Error: No se puede dividir entre cero.') | ||
else: | ||
# Codigo que se ejecuta si no hay ninguna excepcion | ||
print('La divison se realizo correctamente.') | ||
finally: | ||
# Codigo que siempre se ejecuta, haya o no excepciones | ||
print('Este bloque siempre se ejecuta.') | ||
|
||
print('---------------------') | ||
|
||
# Multiples excepciones | ||
try: | ||
resultado = 10 / 0 | ||
except (ZeroDivisionError, TypeError, ValueError) as e: | ||
print(f'Error: {e}') | ||
|
||
|
||
print('---------------------') | ||
|
||
|
||
# Excepciones personalizadas | ||
class MiErrorPersonalizado(Exception): | ||
pass | ||
|
||
|
||
try: | ||
raise MiErrorPersonalizado('Este es un error personalizado.') | ||
except MiErrorPersonalizado as e: | ||
print(e) | ||
|
||
print('---------------------') | ||
|
||
|
||
# Ejemplo: | ||
def dividir(a, b): | ||
try: | ||
resultado = a / b | ||
except ZeroDivisionError: | ||
print('Error: No se puede dividir entre cero.') | ||
except TypeError: | ||
print('Error: Los tipos de datos no son validos') | ||
else: | ||
print(f'El resultado de dividir {a} y {b} es: {resultado}') | ||
finally: | ||
print('Fin del bloque.') | ||
|
||
dividir(3, 4) | ||
dividir(3, 0) | ||
dividir(3, 'a') | ||
|
||
print('---------------------') | ||
|
||
# Extra | ||
|
||
class ValorInvalidoError(Exception): | ||
def __init__(self, mensaje="El valor proporcionado no es válido"): | ||
self.mensaje = mensaje | ||
super().__init__(self.mensaje) | ||
|
||
def procesar_parametros(numero, texto): | ||
if not isinstance(numero, int): | ||
raise TypeError("El primer parámetro debe ser un número entero") | ||
|
||
if not isinstance(texto, str): | ||
raise TypeError("El segundo parámetro debe ser una cadena de texto") | ||
|
||
if numero < 0: | ||
raise ValorInvalidoError("El número debe ser positivo") | ||
|
||
if not texto.strip(): | ||
raise ValueError("El texto no puede estar vacío") | ||
|
||
return f"Número: {numero}, Texto: {texto}" | ||
|
||
|
||
def probar_funcion(): | ||
casos_prueba = [ | ||
(10, "Hola"), # Caso válido | ||
(-5, "Mundo"), # Número negativo | ||
(15, ""), # Texto vacío | ||
("no_numero", "Test"), # Tipo incorrecto | ||
] | ||
|
||
for numero, texto in casos_prueba: | ||
try: | ||
resultado = procesar_parametros(numero, texto) | ||
print(f"¡Éxito! {resultado}") | ||
except ValorInvalidoError as e: | ||
print(f"Error personalizado: {e}") | ||
except TypeError as e: | ||
print(f"Error de tipo: {e}") | ||
except ValueError as e: | ||
print(f"Error de valor: {e}") | ||
except Exception as e: | ||
print(f"Error inesperado: {e}") | ||
finally: | ||
print("La ejecución de este caso ha finalizado") | ||
print("-" * 50) | ||
|
||
|
||
if __name__ == "__main__": | ||
probar_funcion() |