跳转到主要内容
模块 7 · 第 4 课(共 4)课程中的28/36~10 min
模块课程(4/4)

导入和模块

Python 中的 模块 只是一个 .py 文件。使用模块的代码 从另一个文件,您导入它。

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

Python 在哪里寻找模块

Python 在 sys.path 中查找模块,其中包括:

1.运行脚本的目录,2. PYTHONPATH 中的目录,3.已安装的库(site-packages)。

Python
import sys
sys.path     # lista di directory

创建模块

创建mio_modulo.py:

Python
# mio_modulo.py
PI = 3.14159

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

从同一目录中的另一个文件:

Python
import mio_modulo
mio_modulo.area_cerchio(5)   # 78.53975

from mio_modulo import area_cerchio, PI

if __name__ == "__main__":

当脚本被直接执行时,它的特殊变量__name__ 等于 "__main__"。当同一个文件作为模块导入时, __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()

这是可用作可重用文件的文件的标准模式 模块和可执行脚本。

包:模块的文件夹

包含 __init__.py 文件(即使是空文件)的目录将成为 可导入的包:

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

轮到你了

锻炼#python.m7.l4.e1
尝试:0加载中...

从 `math` 模块导入函数 `sqrt`(使用 `from math import sqrt`),然后计算 144 的平方根并将其分配给 `r`。评估“r”。

正在加载编辑器...
显示提示

从数学导入 sqrt

3 次尝试后可用的解决方案

复习练习

锻炼#python.m7.l4.e2
尝试:0加载中...

使用别名“rnd”导入“random”模块(“import random as rnd”),然后使用 rnd.seed(42) 将种子设置为 42,并评估 rnd.randint(1, 100)。

正在加载编辑器...
显示提示

将随机导入为 rnd

3 次尝试后可用的解决方案

额外的挑战

锻炼#python.m7.l4.e3
尝试:0加载中...

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.

正在加载编辑器...
显示提示

sin(0) 产生 0.0,cos(0) 产生 1.0。总和为 1.0。使用 from math import sin, cos。

3 次尝试后可用的解决方案