python中的三种模块导入方法(Python入门基础:模块基础)python基础 / python模块导入基础...

wufei123 发布于 2024-06-30 阅读(5)

模块是一个文件(.py文件),包含变量,类定义语句和与特定任务相关的功能预先装有Python的Python模块称为标准库模块创建我们的模块我们将创建一个名为tempConversion.py的模块,该模块将值从F转换为C,反之亦然。

# tempConversion.py to convert between# between Fahrenheit and Centigrade# function to convert F to C

defto_centigrade(x):return5 * (x - 32) / 9.0# function to convert C to Fdefto_fahrenheit(x):return9 * 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提供了多种在程序中导入模块的方法:导入整个模块:导入模块名要仅导入模块的特定部分:从module_name导入object_name导入模块的所有对象:。

从module_name导入*使用导入的模块导入模块后,我们可以根据以下语法使用导入模块的任何功能/定义:module_name.function_name() 这种引用模块对象的方式称为点表示法如果我们使用导入函数from,则无需提及模块名称和点号即可使用该函数。

示例1:导入整个模块:# importing the moduleimport tempConversion    # using a function of the moduleprint(tempConversion.to_centigrade(

12))    # fetching an object of the moduleprint(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 = 5print("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十六进制转换产生0x55

发表评论:

◎欢迎参与讨论,请在这里发表您的看法、交流您的观点。

河南中青旅行社综合资讯 奇遇综合资讯 盛世蓟州综合资讯 综合资讯 游戏百科综合资讯 新闻61769