我們知道import語句是用來匯入外部模組的,當然還有from...import...也可以,但是其實import實際上是使用builtin函式__import__來工作的。
在一些程式中,我們可以動態地去呼叫函式,如果我們知道模組的名稱(字串)的時候,我們可以很方便的使用動態呼叫。
python**
import glob,os
modules =
for module_file in glob.glob("*-plugin.py"):
try:
module_name,ext = os.path.splitext(os.path.basename(module_file))
module = __import__(module_name)
except importerror:
pass #ignore broken modules
#say hello to all modules
for module in modules:
module.hello()
使用__import__函式獲得特定函式
python**
def getfunctionbyname(module_name,function_name):
module = __import__(module_name)
return getattr(module,function_name)
還可以使用這個函式實現延遲化的模組匯入
python**
class lazyimport:
def __init__(self,module_name):
self.module_name = module_name
self.module = none
def __getattr__(self,name):
if self.module is none:
self.module = __import__(self.module_name)
return getattr(self.module,name)
string = lazyimport("string")
print string.lowercase
python內建函式 python的內建函式 方法
1 input 輸入內容時要將內容用引號引起來 input 請輸入密碼 input 請輸入登入名 name input 請輸入姓名 print hello,name 請輸入姓名 binla hello,binla 在列表後邊追加乙個元素 3 extend 在列表之後追加乙個列表 4 insert 位...
python重寫內建函式 python 內建函式
說明 zip 函式用於將可迭代的物件作為引數,將物件中對應的元素打包成乙個個元組,然後返回由這些元組組成的列表。如果各個迭代器的元素個數不一致,則返回列表長度與最短的物件相同,利用 號操作符,可以將元組解壓為列表。語法 zip iterable1,iterable2,引數 iterable 乙個或多...
python內建函式簡稱 Python內建函式詳解
此文參考python文件,然後結合自己的理解,寫下來,一方面方便自己,讓自己好好學習,順便回憶回憶 另一方面,讓喜歡的盆友也參考一下。經查詢,3.6版本總共有68個內建函式,主要分類如下 數 算 7個 型別轉換 24個 序列操作 8個 物件操作 9個 反射操作 8個 變數操作 2個 互動操作 2個 ...