模块课程(4/4)
导入和模块
Python 中的 模块 只是一个 .py 文件。使用模块的代码
从另一个文件,您导入它。
import 的形式
# 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, evitaPython 在哪里寻找模块
Python 在 sys.path 中查找模块,其中包括:
1.运行脚本的目录,2. PYTHONPATH 中的目录,3.已安装的库(site-packages)。
import sys
sys.path # lista di directory创建模块
创建mio_modulo.py:
# mio_modulo.py
PI = 3.14159
def area_cerchio(r):
return PI * r * r从同一目录中的另一个文件:
import mio_modulo
mio_modulo.area_cerchio(5) # 78.53975
from mio_modulo import area_cerchio, PIif __name__ == "__main__":
当脚本被直接执行时,它的特殊变量__name__
等于 "__main__"。当同一个文件作为模块导入时,
__name__ 等于模块名称。
# 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 文件(即使是空文件)的目录将成为
可导入的包:
mio_pkg/
__init__.py
utenti.py
pagamenti.py
from mio_pkg import utenti
from mio_pkg.utenti import crea_utente轮到你了
从 `math` 模块导入函数 `sqrt`(使用 `from math import sqrt`),然后计算 144 的平方根并将其分配给 `r`。评估“r”。
显示提示
从数学导入 sqrt
3 次尝试后可用的解决方案
复习练习
使用别名“rnd”导入“random”模块(“import random as rnd”),然后使用 rnd.seed(42) 将种子设置为 42,并评估 rnd.randint(1, 100)。
显示提示
将随机导入为 rnd
3 次尝试后可用的解决方案
额外的挑战
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 次尝试后可用的解决方案