Python import 的用法
我們剛開始接觸python 看到了很多python 的很多庫 比如添加log 的庫logging
import logginglogging.error("error:直接輸入log日志")
在看下打印的結果
我們可以從源碼里面看到 error 是__init__.py 里面的一個函數
我們要使用__init__.py 需要先導入logging ,也就有了 import logging
這樣可以看出 import 1中用法 :
1 import? module(模塊名)
假如多導入幾次看下面的效果
這個就是一個模塊只會被導入一次,多次導入無效。
下面 寫一個demo 練習下import? module(模塊名)
下面創建2個.py 文件 1個是function.py 一個是use.py
function.py 里面 的內容如下
#!/usr/bin/python3def my_function():print("Hello!")
練習 1?
現在想在use.py 里面調用 my_function 函數
這里我們使用import? module(模塊名)
在use.py 里面寫
# 引入模塊
import function
# 調用function.py 中的my_function 函數
function.my_function()
運行use.py 查看下 log
練習 2?
use.py 傳參數給 function.py
在?function.py 里面新增一個帶參數的函數my_function1
#!/usr/bin/python3def my_function():print("Hello!")def my_function1(name):print("Hello!" + name)
use.py 傳參數
# 引入模塊
import function
# 調用function.py 中的my_function 函數
function.my_function()# 調用function.py 中的my_function 函數 并傳遞一個name
function.my_function1("小牧")
打印結果
2 from … import 語句 :一般的格式為 from 模塊名 import 函數名
這個一般是只調用一個模塊里面的一個指定的函數
例如:在function.py 里面新增一個?my_function2
def my_function2(name):print("How Are You!" + name)
use.py 里面?
# 引入模塊
from function import my_function2my_function2("小牧")
對比上面2個例子可以很明顯看到 應用函數my_function2的使用 這里是直接使用的,沒有在前面使用模塊名.函數
3?from … import * :一般格式為from 模塊名 import *
這個就是引入模塊名之后,里面的函數都可以調用了
例如在function.py 里面添加 3個函數
#!/usr/bin/python3def my_function():print("Hello!")def my_function1(name):print("Hello!" + name)def my_function2(name):print("How Are You!" + name)
在 use.py 里面使用 from function import *
from function import *
my_function()
my_function1("小牧")
my_function2("小牧")
打印結果
總結
以上是生活随笔為你收集整理的Python import 的用法的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 印章多少钱啊?
- 下一篇: Python ModuleNotFou