Fundamentos de Programaci贸n y Python
驴Por qu茅 aprender Python?
Introducci贸n a Python
Conceptos B谩sicos de Programaci贸n
Pr谩ctica: Te doy la bienvenida a los ejercicios interactivos
Manipulaci贸n de Cadenas de Texto en Python
Enteros, Flotantes y Booleanos
Todo lo que Debes Saber sobre print en Python
Operaciones Matem谩ticas en Python
Operaciones de Entrada/Salida en Consola
Colecci贸n y Procesamiento de Datos en Python
Listas
M茅todo slice
Listas de m谩s dimensiones y Tuplas
Aplicaci贸n de Matrices
Diccionarios
Comprehension Lists en Python (CLASE NUEVA)
Control de Flujo en Python
Estructuras condicionales
Bucles y Control de Iteraciones
Generadores e Iteradores
Funciones y Manejo de Excepciones en Python
Uso de Funciones en Python
Funciones Lambda y Programaci贸n Funcional en Python
驴C贸mo realizar una funci贸n recursiva en Python?
Manejo de Excepciones y Uso de Pass (CLASE NUEVA)
Programaci贸n Orientada a Objetos en Python
Fundamentos de Programaci贸n Orientada a Objetos en Python
Ejercicio Biblioteca con POO
Herencia en POO con Python
Objetos heredados
Los 4 pilares de la programacion orientada a objetos
Uso de super() en Python (CLASE NUEVA)
Superando los Fundamentos de Programaci贸n Orientada a Objetos en Python
Lectura y escritura de archivos
Manejo de Archivos .TXT (CLASE NUEVA)
Manejo de Archivos CSV (CLASE NUEVA)
Manejo de Archivos JSON (CLASE NUEVA)
Biblioteca est谩ndar de Python
Biblioteca est谩ndar en Python (CLASE NUEVA)
Librer铆a Os, Math y Random (CLASE NUEVA)
Librer铆a Statistics y An谩lisis Estad铆stico (CLASE NUEVA)
Proyecto final: Guerra naval
Conceptos avanzados de Python
Recapitulaci贸n de lo aprendido hasta ahora
Escribir c贸digo Pythonico y profesional
Comentarios y Docstrings en Python
Scope y closures: variables locales y globales
Anotaciones de tipo
Validaci贸n de tipos en m茅todos
Librer铆a Collections y Enumeraciones
Decoradores
Decoradores en Python
Decoradores anidados y con par谩metros
Uso de Decoradores en clases y m茅todos
M茅todos y estructura de clases en Python
M茅todos m谩gicos
Sobrecarga de operadores
Implementaci贸n de `if __name__ == "__main__":`
Metaprogramaci贸n en Python
Uso de *args y **kwargs
M茅todos privados y protegidos
Gesti贸n avanzada de propiedades
M茅todos est谩ticos y de clase avanzados
Programaci贸n concurrente y as铆ncrona
Introducci贸n a la concurrencia y paralelismo
Threading y multiprocessing en Python
Asincronismo con asyncio
Asincronismo y concurrencia
Creaci贸n de m贸dulos y paquetes
Creaci贸n de m贸dulos en Python
Gesti贸n de paquetes
Publicaci贸n de paquetes en PyPI
Proyecto final
Implementaci贸n de un sistema completo
Implementaci贸n de un Sistema Completo
You don't have access to this class
Keep learning! Join and start boosting your career
args
and kwargs
and how do they help you in programming?In the world of programming, especially when working with functions, we encounter situations where the number of arguments we are going to receive is uncertain. This is where args
and kwargs
become indispensable allies. These mechanisms allow us to handle a variable number of arguments or parameters, giving flexibility and dynamism to the functions we create.
*args
for variable arguments?*args
is a tool used to receive an indefinite number of arguments. In Python, when we define a function and precede it with an asterisk *
, we indicate that we are ready to receive multiple arguments.
def sum_numbers(*args): return sum(args)
# Call function with different number of argumentsprint(sum_numbers(1, 2, 3, 4, 4, 5)) # Return 15print(sum_numbers(1, 2)) # Return 3print(sum_numbers(7, 8, 9, 10, 10)) # Return 34.
args
are stored in an immutable tuple.**kwargs
?When you need to work with arguments that have labels (i.e., key-value pairs), the appropriate method is **kwargs
. By prefixing two asterisks **
to our variable, we indicate that we are ready to receive named arguments.
def print_info(**kwargs): for key, value in kwargs.items(): print(f"{key}: {value}")
# Function call with different argumentsprint_info(name="Carlos", age=30, city="Bogot谩")# Output:# name: Carlos# age: 30# city: Bogot谩.
kwargs
is stored as a dictionary.args
and kwargs
in classes?In object-oriented programming, it is also possible to use args
and kwargs
, especially to provide flexibility in class initialization.
class Employee: def __init__(self, name, *skills, **details): self.name = name self.skills = skills self.details = details
def show_info(self): print(f "Name: {self.name}") print(f "Skills: {self.skills}") print(f "Details: {self.details}")
# Creation of an object and instance of the classemployee = Employee("Carlos", "Python", "Java", "C++ ", age=30, city="Bogot谩")employee.show_info()
Unpacking allows you to extract values from lists or dictionaries and pass them to a function without having to specify each value individually. This can be done with either args
(using *
) or kwargs
(using **
).
def sum(a, b, c): return a + b + c
# Unpacked listvalues = [1, 2, 3]print(sum(*values)) # Return 6
def show_information(name, age): print(f "Name: {name}, Age: {age}")
# Unpacked dictionarydata = {'name': 'Carlos', 'age': 30}show_information(**data)
To put these concepts into practice, we suggest you create functions that can receive price lists and applicable discounts using *args
and **kwargs
. The key is to discern when one approach or the other is necessary and how we can take advantage of the dynamism offered by these mechanisms.
Programming with args
and kwargs
not only offers greater flexibility, but also improves the readability and efficiency of our code. We encourage you to continue exploring these concepts and apply them in your daily projects.
Contributions 46
Questions 1
Want to see more contributions, questions and answers from the community?