Es. Python tutorial - Moduli e pacchetti 2
Versione italiana
Esercizi
11. Creazione di un Modulo con una Classe
Crea un modulo person.py che contenga una classe
Person con attributi name e age e
un metodo greet() che stampa un saluto. Importa la classe
in un altro script e usala.
12. Importazione Multipla
Crea un modulo math_ops.py con le funzioni
add(a, b), subtract(a, b) e
multiply(a, b). Importa tutte le funzioni in un altro
script usando from ... import ....
13. Creazione
di un Pacchetto con __init__.py
Crea un pacchetto animals con due moduli:
dog.pycon una funzionebark()che stampa"Woof!".cat.pycon una funzionemeow()che stampa"Meow!".
Definisci un__init__.pyche importa entrambe le funzioni e usale in uno script.
14. Uso di
as per Rinominare le Importazioni
Crea un modulo date_utils.py con una funzione
get_year(date_str) che estrae l’anno da una stringa di data
nel formato "YYYY-MM-DD". Importalo con un alias e
usalo.
15. Modulo con una Lista di Costanti
Crea un modulo constants.py con una lista di numeri
primi chiamata PRIMES. Importa il modulo in un altro script
e stampa la lista.
16. Creazione di un Modulo con una Funzione Ricorsiva
Crea un modulo factorial.py con una funzione
calc_factorial(n) che calcola il fattoriale di un numero
ricorsivamente. Usalo in uno script.
17. Importazione di un Modulo Personalizzato da un Percorso Specifico
Crea un modulo custom_module.py in una directory
separata e scrivi uno script che lo importi usando
sys.path.append().
18. Uso
di __all__ per Controllare le Esportazioni
Crea un modulo math_tools.py con tre funzioni:
square(n), cube(n), e sqrt(n).
Definisci __all__ in modo che solo square e
cube siano accessibili con
from math_tools import *.
19. Lettura di un File da un Modulo
Crea un modulo file_reader.py con una funzione
read_file(filename) che legge e stampa il contenuto di un
file di testo.
20. Creazione di un Modulo con Decoratori
Crea un modulo decorators.py con un decoratore
log_function_call che stampa un messaggio prima di eseguire
una funzione. Usalo su una funzione say_hello() in un altro
script.
Soluzioni
# 11. Creazione di un Modulo con una Classe
# person.py
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
def greet(self):
print(f"Hello, my name is {self.name} and I'm {self.age} years old.")
# script.py
from person import Person
p = Person("Alice", 30)
p.greet() # Output: "Hello, my name is Alice and I'm 30 years old."
# 12. Importazione Multipla
# math_ops.py
def add(a, b):
return a + b
def subtract(a, b):
return a - b
def multiply(a, b):
return a * b
# script.py
from math_ops import add, subtract, multiply
print(add(3, 2)) # Output: 5
print(subtract(7, 3)) # Output: 4
print(multiply(4, 6)) # Output: 24
# 13. Creazione di un Pacchetto con `__init__.py`
# animals/dog.py
def bark():
print("Woof!")
# animals/cat.py
def meow():
print("Meow!")
# animals/__init__.py
from .dog import bark
from .cat import meow
# script.py
import animals
animals.bark() # Output: "Woof!"
animals.meow() # Output: "Meow!"
# 14. Uso di `as` per Rinominare le Importazioni
# date_utils.py
def get_year(date_str):
return date_str.split("-")[0]
# script.py
import date_utils as du
print(du.get_year("2025-02-14")) # Output: "2025"
# 15. Modulo con una Lista di Costanti
# constants.py
PRIMES = [2, 3, 5, 7, 11, 13, 17, 19]
# script.py
import constants
print(constants.PRIMES) # Output: [2, 3, 5, 7, 11, 13, 17, 19]
# 16. Creazione di un Modulo con una Funzione Ricorsiva
# factorial.py
def calc_factorial(n):
return 1 if n == 0 else n * calc_factorial(n - 1)
# script.py
import factorial
print(factorial.calc_factorial(5)) # Output: 120
# 17. Importazione di un Modulo Personalizzato da un Percorso Specifico
# script.py
import sys
sys.path.append("/path/to/custom/directory") # Modifica con il percorso corretto
import custom_module
custom_module.some_function()
# 18. Uso di `__all__` per Controllare le Esportazioni
# math_tools.py
__all__ = ["square", "cube"]
def square(n):
return n * n
def cube(n):
return n * n * n
def sqrt(n):
return n ** 0.5
# script.py
from math_tools import *
print(square(4)) # Output: 16
print(cube(3)) # Output: 27
# 19. Lettura di un File da un Modulo
# file_reader.py
def read_file(filename):
with open(filename, "r") as f:
print(f.read())
# script.py
import file_reader
file_reader.read_file("test.txt") # Stampa il contenuto di "test.txt"
# 20. Creazione di un Modulo con Decoratori
# decorators.py
def log_function_call(func):
def wrapper(*args, **kwargs):
print(f"Calling function: {func.__name__}")
return func(*args, **kwargs)
return wrapper
# script.py
from decorators import log_function_call
@log_function_call
def say_hello():
print("Hello, world!")
say_hello()
# Output:
# Calling function: say_hello
# Hello, world!English version
Exercises
11. Creating a Module with a Class
Create a module person.py containing a class
Person with attributes name and
age and a method greet() that prints a
greeting. Import the class into another script and use it.
12. Multiple Imports
Create a module math_ops.py with the functions
add(a, b), subtract(a, b) and
multiply(a, b). Import all the functions into another
script using from ... import ....
13. Creating a
Package with __init__.py
Create a package animals with two modules:
dog.pywith a functionbark()that prints"Woof!".cat.pywith ameow()function that prints"Meow!". Define a__init__.pythat imports both functions and use them in a script.
14. Using as to
Rename Imports
Create a module date_utils.py with a function
get_year(date_str) that extracts the year from a date
string in the format "YYYY-MM-DD". Import it with an alias
and use it.
15. Module with a List of Constants
Create a module constants.py with a list of primes
called PRIMES. Import the module into another script and
print the list.
16. Creating a Module with a Recursive Function
Create a module factorial.py with a function
calc_factorial(n) that calculates the factorial of a number
recursively. Use it in a script.
17. Importing a Custom Module from a Specific Path
Create a module custom_module.py in a separate directory
and write a script that imports it using
sys.path.append().
18. Using
__all__ to Control Exports
Create a module math_tools.py with three functions:
square(n), cube(n), and sqrt(n).
Define __all__ so that only square and
cube are accessible with
from math_tools import *.
19. Reading a File from a Module
Create a module file_reader.py with a function
read_file(filename) that reads and prints the contents of a
text file.
20. Creating a Module with Decorators
Create a module decorators.py with a decorator
log_function_call that prints a message before executing a
function. Use it on a say_hello() function in another
script.
Solutions
#11. Creating a Module with a Class
# person.py
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
def greet(self):
print(f"Hello, my name is {self.name} and I'm {self.age} years old.")
# script.py
from person import Person
p = Person("Alice", 30)
p.greet() # Output: "Hello, my name is Alice and I'm 30 years old."
# 12. Multiple Import
# math_ops.py
def add(a, b):
return a + b
def subtract(a, b):
return a - b
def multiply(a, b):
return a * b
# script.py
from math_ops import add, subtract, multiply
print(add(3, 2)) # Output: 5
print(subtract(7, 3)) # Output: 4
print(multiply(4, 6)) # Output: 24
# 13. Creating a Package with `__init__.py`
# animals/dog.py
def bark():
print("Woof!")
# animals/cat.py
def meow():
print("Meow!")
# animals/__init__.py
from .dog import bark
from .cat import meow
# script.py
import animals
animals.bark() # Output: "Woof!"
animals.meow() # Output: "Meow!"
# 14. Using `as` to Rename Imports
# date_utils.py
def get_year(date_str):
return date_str.split("-")[0]
# script.py
import date_utils as du
print(du.get_year("2025-02-14")) # Output: "2025"
# 15. Module with a List of Constants
# constants.py
PRIMES = [2, 3, 5, 7, 11, 13, 17, 19]
# script.py
import constants
print(constants.PRIMES) # Output: [2, 3, 5, 7, 11, 13, 17, 19]
# 16. Creating a Module with a Recursive Function
# factorial.py
def calc_factorial(n):
return 1 if n == 0 else n * calc_factorial(n - 1)
# script.py
import factorial
print(factorial.calc_factorial(5)) # Output: 120
# 17. Importing a Custom Module from a Specific Path
# script.py
import sys
sys.path.append("/path/to/custom/directory") # Edit with the correct path
import custom_module
custom_module.some_function()
# 18. Using `__all__` to Control Exports
# math_tools.py
__all__ = ["square", "cube"]
def square(n):
return n * n
def cube(n):
return n * n * n
def sqrt(n):
return n ** 0.5
# script.py
from math_tools import *
print(square(4)) # Output: 16
print(cube(3)) # Output: 27
# 19. Reading a File from a Module
# file_reader.py
def read_file(filename):
with open(filename, "r") as f:
print(f.read())
# script.py
import file_reader
file_reader.read_file("test.txt") # Print the contents of "test.txt"
# 20. Creazione di un Modulo con Decoratori
# decorators.py
def log_function_call(func):
def wrapper(*args, **kwargs):
print(f"Calling function: {func.__name__}")
return func(*args, **kwargs)
return wrapper
# script.py
from decorators import log_function_call
@log_function_call
def say_hello():
print("Hello, world!")
say_hello()
# Output:
# Calling function: say_hello
# Hello, world!
Commenti
Posta un commento