Ana içeriğe geç
eLearner.app
Modül 7 · Ders 4 ders 4Kurstaki 28/36~10 min
Modül dersleri (4/4)

içe aktarma ve modüller

A module in Python is simply a .py file. To use the code of a module from another file, you import it.

Forms of import

Python
# 1) import del modulo intero
import math
math.sqrt(16)        # 4.0
math.pi              # 3.14159...

# 2) import di nomi specifici
from math import sqrt, pi
sqrt(16)             # ora direttamente disponibile
pi

# 3) import con alias
import numpy as np      # convenzione idiomatica
from datetime import datetime as dt

# 4) import "star" (sconsigliato)
from math import *      # inquina il namespace, evita

Where Python looks for modules

Python looks for modules in sys.path, which includes:

  1. the directory of the running script,
  2. the directories in PYTHONPATH,
  3. the installed libraries (site-packages).
Python
import sys
sys.path     # lista di directory

Creating a module

Create mio_modulo.py:

Python
# mio_modulo.py
PI = 3.14159

def area_cerchio(r):
    return PI * r * r

From another file in the same directory:

Python
import mio_modulo
mio_modulo.area_cerchio(5)   # 78.53975

from mio_modulo import area_cerchio, PI

if __name__ == "__main__":

When a script is executed directly, its special variable __name__ equals "__main__". When the same file is imported as a module, __name__ equals the module name.

Python
# strumento.py

def fai_qualcosa():
    print("lavoro!")

if __name__ == "__main__":
    # eseguito solo se lanci `python strumento.py`
    # NON viene eseguito se qualcuno importa questo file
    fai_qualcosa()

This is the standard pattern for files that can serve as both a reusable module and an executable script.

Packages: folders of modules

A directory containing an __init__.py file (even an empty one) becomes an importable package:

Code
mio_pkg/
    __init__.py
    utenti.py
    pagamenti.py
Python
from mio_pkg import utenti
from mio_pkg.utenti import crea_utente

Your turn

Egzersiz#python.m7.l4.e1
Denemeler: 0Yükleniyor…

Import the function `sqrt` from the `math` module (with `from math import sqrt`), then compute the square root of 144 and assign it to `r`. Evaluate `r`.

Düzenleyici yükleniyor…
İpucu göster

from math import sqrt

3 denemeden sonra çözüm mevcut

Review exercise

Egzersiz#python.m7.l4.e2
Denemeler: 0Yükleniyor…

Import the `random` module with alias `rnd` (`import random as rnd`), then set the seed to 42 with rnd.seed(42), and evaluate rnd.randint(1, 100).

Düzenleyici yükleniyor…
İpucu göster

import random as rnd

3 denemeden sonra çözüm mevcut

Additional challenge

Egzersiz#python.m7.l4.e3
Denemeler: 0Yükleniyor…

Import the `sin` and `cos` functions directly from the `math` module using `from ... import ...`. Calculate the sum of `sin(0)` and `cos(0)`, store it in `trig_sum`, and evaluate it.

Düzenleyici yükleniyor…
İpucu göster

sin(0) yields 0.0, cos(0) yields 1.0. The sum is 1.0. Use from math import sin, cos.

3 denemeden sonra çözüm mevcut