2014/02/02

Python 3.3 define module and import module

任何程式語言的代碼應該要可重複利用,而不是一次性,可將方法定義成函數或模組,讓這些代碼可以重複使用

首先,定義一個test2的python檔案,程式碼如下:

def a():
 print("123")

def b():
 print("456")

def c():
 print("789")


test2定義了a、b以及c三個方法,分別印出『123』、『456』和『789』



在撰寫一個test的python檔案,程式碼如下:
import test2

try:
 test2.a()
 test2.b()
 test3.c()
 a()
except Exception as e:
 print()


from test2 import a
from test2 import b
from test2 import c

a()
b()
c()

python在import的方式有分三種:
import 類別名稱
from 類別名稱 import 模組1, 模組2...
from 類別名稱 import *

由import三種方式看test的檔案

第一個方法直接將模組import,得加上類別名稱才能使用方法,不能省略類別名稱,否則會錯誤
第二個方法則是import特定方法,亦即可直接呼叫方法,並省略類別名稱
第三個方法則是將該類別的方法都導入近來,如同第二個方法


不過一和二的方法可以透過『as』給予別名,避免類別名稱或方法名稱有衝突,程式碼如下:

import test2 as t

try:
 t.a()
 t.b()
 test2.c()
except Exception as e:
 print(e, "\n")


from test2 import a as aa
from test2 import b as bb
from test2 import c as cc

aa()
bb()
c()




參考資料:
http://docs.python.org/3/tutorial/modules.html