5.5. Creación de módulos
Has visto cómo usar módulos como random
, math
, y turtle
, pero ¿cómo crearías un módulo?
¡Cada vez que has escrito un script de Python has creado un módulo!
Un módulo Python es solo un archivo de código fuente de Python. Consideremos el archivo de Python que se muestra a continuación.
coffee_shop.py
"""
The coffee shop module contains functions and contains variables
important to implementing a coffee shop.
"""
# Set some variables
shop_name = "Runestone Brew House"
coffee_sizes = ["small", "medium", "large"]
coffee_roasts = ["hot chocolate", "light", "medium", "dark", "espresso"]
Este es un guión de Python llamado coffee_shop.py
que contiene tres variables: shop_name
, coffee_sizes
, y coffee_roasts
. El shop_name
es una cadena, coffee_sizes
es una lista que contiene cadenas, y coffee_roasts
también es una lista que contiene cadenas.
Un módulo es otro nombre para:
Activity: 5.5.1 Multiple Choice (question4_5_1)
R! B.
Eso es genial! Tenemos los conceptos básicos de una cafetería. Todo lo que necesitas es un café y tazas asadas. Estás listo para ir.
Sin embargo, si intenta ejecutar ese código, no hace mucho que sea visible para un usuario ...
¿Cómo podemos usar el coffee_shop
¿módulo? Podemos importarlo y usarlo en otros archivos de código fuente
de Python. Consideremos el archivo de Python que se muestra a
continuación.
coffee_customer.py
import coffee_shop
# Output the information we know from the module
print("Welcome to", coffee_shop.shop_name)
print("Available sizes:", coffee_shop.coffee_sizes)
print("Available roasts:", coffee_shop.coffee_roasts)
Este es un guión de Python llamado coffee_customer.py
que importa nuestro coffee_shop
Módulo, luego imprime la información de ese módulo.
Nota
Los archivos del módulo deben estar en el mismo directorio en su computadora para que Python sepa cómo importarlos automáticamente
Crea un módulo por:
Actividad: 5.5.2 Opción múltiple (pregunta4_5_2)
Usamos notación de puntos para agarrar el shop_name
, coffee_sizes
, y coffee_roasts
variables del coffee_shop
módulo. Luego los imprimimos como partes de buenos mensajes.
Sin embargo, las variables no son lo único que podemos colocar en los módulos ... Podemos poner cualquier código de Python válido en ellas.
¡Vamos a mejorar nuestra cafetería!
coffee_shop.py
>>"""
The coffee shop module contains functions and contains variables
important to implementing a coffee shop.
>>"""
>># Set some variables
>>shop_name = "Runestone Brew House"
>>coffee_sizes = ["small", "medium", "large"]
>>coffee_roasts = ["hot chocolate", "light", "medium", "dark", "espresso"]
>>def order_coffee(size, roast):
"""
Take an order from a user
:param size: a string containing one of the coffee_sizes
:param roast: a string containing one of the coffee_roasts
:return: a message about the coffee order
"""
return "Here's your {} coffee roasted {}".format(size, roast)
El contenido de archivo anterior está presente, pero ahora también hay un order_coffee
función que toma dos argumentos, size
y roast
.
Además, ¡mira todos los increíbles comentarios allí!
Comentarios del módulo
Es importante incluir comentarios de encabezado en su módulo que expliquen lo que hace el módulo.
Comentarios de funciones
Las funciones son el próximo capítulo, pero los comentarios utilizados aquí demuestran un estilo de documentación de Python común.
OK, así que tenemos una función en nuestro módulo ahora, usémoslo.
coffee_customer.py
# Import the module with coffee_shop functionality
import coffee_shop
# Output the information we know from the module
print("Welcome to", coffee_shop.shop_name)
print("Available sizes:", coffee_shop.coffee_sizes)
print("Available roasts:", coffee_shop.coffee_roasts)
# Get some inputs from the user
order_size = input("What size coffee do you want? ")
order_roast = input("What roast do you want? ")
# Send the order to the coffee shop module
shop_says = coffee_shop.order_coffee(order_size, order_roast)
# Print out whatever it gave back to us
print(shop_says)
¿Qué determina el nombre de nuestra importación?
Actividad: 5.5.3 Opción múltiple (pregunta4_5_3)
Agregamos algunas líneas a nuestro coffee_customer
script ... ahora después de imprimir datos muy bien, coffee_customer
le pide al usuario un tamaño y un asado. Estos son los parámetros requeridos por nuestro order_coffee
función en el coffee_shop
¡módulo!
Llamar al order_coffee
Funcionar con notación de puntos , al igual que recuperar valores variables. La llamada de función es la línea que dice shop_says = coffee_shop.order_coffee(order_size, order_roast)
. La función devuelve algo, por lo que guardamos eso en shop_says
. La siguiente línea imprime lo que dijo la tienda.
¡Las cafeterías hacen más que solo café! Quizás quieras un poco de leche. Necesitamos agregar algo de funcionalidad a nuestra cafetería. Compruébalo a continuación.
coffee_shop.py
"""
The coffee shop module contains functions and contains variables
important to implementing a coffee shop.
"""
# Set some variables
shop_name = "Runestone Brew House"
coffee_sizes = ["small", "medium", "large"]
coffee_roasts = ["hot chocolate", "light", "medium", "dark", "espresso"]
def order_coffee(size, roast):
"""
Take an order from a user
:param size: a string containing one of the coffee_sizes
:param roast: a string containing one of the coffee_roasts
:return: a message about the coffee order
"""
return "Here's your {} coffee roasted {}".format(size, roast)
def add_milk_please(fat_content):
"""
Pretend like we're adding some milk to a coffee
:param fat_content: a string or integer containing the milkfat content
:return: a message about having added the milk
"""
return "I've added the {}% milk".format(fat_content)
Se llama a la nueva función add_milk_please
y se necesita un parámetro: el fat_content
. Devuelve una cadena explicando lo que sucedió.
Esto es genial. Pero la función no va a hacer nada por sí solo. Tenemos que llamarlo. Consulte la actualización de nuestro coffee_customer
Script a continuación.
coffee_customer.py
# Import the module with coffee_shop functionality
import coffee_shop
# Output the information we know from the module
print("Welcome to", coffee_shop.shop_name)
print("Available sizes:", coffee_shop.coffee_sizes)
print("Available roasts:", coffee_shop.coffee_roasts)
# Get some inputs from the user
order_size = input("What size coffee do you want? ")
order_roast = input("What roast do you want? ")
# Send the order to the coffee shop module
shop_says = coffee_shop.order_coffee(order_size, order_roast)
# Print out whatever it gave back to us
print(shop_says)
# See if the user wants to add milk
add_milk_response = input("Do you want to add milk (y/n)? ")
# Convert the response to lowercase, then check for a "yes" answer
if "y" in add_milk_response.lower():
milk_fat = input("What percent milk do you want added? ")
shop_says = coffee_shop.add_milk_please(milk_fat)
# Print out whatever it gave back to us
print(shop_says)
Que se puso elegante! Estábamos pediendo café, ¡pero ahora el usuario puede optar por agregar leche! La selección está en un par de capítulos, pero si lees ese código como el inglés, verás lo que está pasando.
La llamada a add_milk_please
sucede allí mismo, se parece al otro: shop_says = coffee_shop.add_milk_please(milk_fat)
.
Vamos a terminar esta cafetería. Pero, es mejor que dejes una propina. Agregaremos otra función a nuestra cafetería para habilitar eso.
coffee_shop.py
"""
The coffee shop module contains functions and contains variables
important to implementing a coffee shop.
"""
# Set some variables
shop_name = "Runestone Brew House"
coffee_sizes = ["small", "medium", "large"]
coffee_roasts = ["hot chocolate", "light", "medium", "dark", "espresso"]
def order_coffee(size, roast):
"""
Take an order from a user
:param size: a string containing one of the coffee_sizes
:param roast: a string containing one of the coffee_roasts
:return: a message about the coffee order
"""
return "Here's your {} coffee roasted {}".format(size, roast)
def add_milk_please(fat_content):
"""
Pretend like we're adding some milk to a coffee
:param fat_content: a string or integer containing the milkfat content
:return: a message about having added the milk
"""
return "I've added the {}% milk".format(fat_content)
def give_tip(tip_amount):
"""
Take a tip from the user, then be happy about it
:param tip_amount: the tip amount
:return: nothing
"""
print("Thank you so much! We don't make a ton of money.")
# Not having a "return" statement causes our function to return None
Agregamos el give_tip
función que toma un parámetro, el tip_amount
.
En realidad, no hacemos nada con ese parámetro ... pero si nos
estábamos siendo más elegantes con la cafetería, podríamos agregarlo a
la factura del cliente, podríamos imprimirlo, o podríamos reprender al
cliente por ser demasiado barato ... ¡aquí solo seguimos un
agradecimiento al usuario! Bein 'Friendly es importante.
¿Cómo llamamos a esto de nuestro coffee_customer
¿guion?
coffee_customer.py
# Import the module with coffee_shop functionality
import coffee_shop
# Output the information we know from the module
print("Welcome to", coffee_shop.shop_name)
print("Available sizes:", coffee_shop.coffee_sizes)
print("Available roasts:", coffee_shop.coffee_roasts)
# Get some inputs from the user
order_size = input("What size coffee do you want? ")
order_roast = input("What roast do you want? ")
# Send the order to the coffee shop module
shop_says = coffee_shop.order_coffee(order_size, order_roast)
# Print out whatever it gave back to us
print(shop_says)
# See if the user wants to add milk
add_milk_response = input("Do you want to add milk (y/n)? ")
# Convert the response to lowercase, then check for a "yes" answer
if "y" in add_milk_response.lower():
milk_fat = input("What percent milk do you want added? ")
shop_says = coffee_shop.add_milk_please(milk_fat)
# Print out whatever it gave back to us
print(shop_says)
# They better give a tip...
print("THAT'S GOOD COFFEE! Very good. Your brain is working again.")
print("You better give a tip.")
tip_amount = input("Tip amount? ")
coffee_shop.give_tip(tip_amount)
Nuestra llamada de función está ahí en la última línea.
No hay comentarios.:
Publicar un comentario