什么是模块?
模块是包含一组函数的文件,希望在应用程序中引用。
如需创建模块,只需将所需代码保存在文件扩展名为 .py 的文件
在名为test.py
的文件中保存代码
def myfunc(name):
print("Hello, " + name)
现在,我们就可以用import
语句来使用我们刚刚创建的模块
导入名为test
的模块,并调用myfunc
函数
import test
test.myfunc("Bill")
**注意:**如果使用模块中的函数时,可以用以下语法:module_name.function_name
模块中的变量
模块可以包含已经描述的函数,但也可以包含各种类型的变量(数组、字典、对象等):
在文件test.py
中保存代码:person = {"name": "Bill","age": 18,"country": "USA"}
导入名为test
的模块,并访问 person 字典
import test
a = test.person["age"]
print(a)
重命名模块
在导入模块时使用as
关键字创建别名
为 test 创建别名ts
import test as ts
a = ts.person["age"]
print(a)
内建模块
Python 中有几个内建模块,您可以随时导入。
导入并使用platform
模块
import platform
x = platform.system()
print(x)
使用 dir() 函数
dir()
是一个内置函数可以列出模块中的所有函数名或变量名
import platform
x = dir(platform)
print(x)
**注意:**dir() 函数可用于所有模块,也可用于您自己创建的模块。
从模块导入
使用from
关键字选择仅从模块导入部件
名为 mymodule 的模块拥有一个函数和一个字典,仅从模块导入 person字典:
test.py
:
def test(name):
print("Hello, " + name)
person = {"name": "Bill","age": 18,"country": "USA"}
引用文件:
from test import person
print (person["age"])
想白嫖python自动化,加我vx:810295842