Python入门:模块基础

本文介绍了如何创建Python模块,并展示了不同方式导入模块及其使用的实例。此外,还概述了Python标准库的一些基本功能。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

模块是一个文件(.py文件),包含变量,类定义语句和与特定任务相关的功能。预先装有Python的Python模块称为标准库模块。

创建我们的模块

我们将创建一个名为tempConversion.py的模块,该模块将值从F转换为C,反之亦然。

# tempConversion.py to convert between
# between Fahrenheit and Centigrade
  
# function to convert F to C
def to_centigrade(x):
      return 5 * (x - 32) / 9.0
  
# function to convert C to F
def to_fahrenheit(x):
       return 9 * x / 5.0 + 32
  
# constants
  
# water freezing temperature(in Celcius)
FREEZING_C = 0.0  
 
# water freezing temperature(in Fahrenheit)     
FREEZING_F = 32.0      

现在保存此python文件并创建模块。导入后,该模块可以在其他程序中使用。

 

导入模块

在python中,为了使用模块,必须将其导入。Python提供了多种在程序中导入模块的方法:

  1. 导入整个模块:导入模块名

  2. 要仅导入模块的特定部分:从module_name导入object_name

  3. 导入模块的所有对象:从module_name导入*

使用导入的模块

导入模块后,我们可以根据以下语法使用导入模块的任何功能/定义:

module_name.function_name() 

这种引用模块对象的方式称为点表示法。
如果我们使用导入函数from,则无需提及模块名称和点号即可使用该函数。

示例1:导入整个模块:

# importing the module
import tempConversion
  
# using a function of the module
print(tempConversion.to_centigrade(12))
  
# fetching an object of the module
print(tempConversion.FREEZING_F)

输出:

-11.11111111111111
32.0

示例2:导入模块的特定组件:

# importing the to_fahrenheit() method 
from tempConversion import to_fahrenheit 

# using the imported method 
print(to_fahrenheit(20)) 

# importing the FREEZING_C object 
from tempConversion import FREEZING_C 

# printing the imported variable 
print(FREEZING_C)

输出:

68.0
0.0

 

​Python标准库功能

python解释器内置了许多始终可用的功能。要使用python的这些内置函数,请直接调用函数,例如function_name()。一些内置的库函数是:input(),int(),float()等

num = 5
print("Number entered = ", num)
  
# oct() converts to octal number-string
onum = oct(num)   
  
# hex() coverts to hexadecimal number-string     
hnum = hex(num)     
     
print("Octal conversion yields", onum)
print("Hexadecimal conversion yields", hnum)
print(num)

输出:

输入的数字= 5
八进制转换得出0o5
十六进制转换产生0x5
5

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值