# Python - Day 4
###### tags: `Python`
## 模組 Module
* 獨立的程式檔案,可重複載入
* 先載入再使用
* 很多內建模組
### 使用方法
1. 載入
```python=
import abc #以實際名稱載入
import abc as a #以別名載入
```
2. 基本語法
```python=
import sys
print ( sys.platform ) #印出作業系統
print ( sys.maxsize ) #印出整數型態的最大值
print ( sys.path ) #印出搜尋模組的路徑
```
```python=
import sys as s #別名!
print ( s.platform ) #印出作業系統
print ( s.maxsize ) #印出整數型態的最大值
print ( s.path ) #印出搜尋模組的路徑
```
### 自訂模組
1. 寫出主程式
2. 寫出模組
3. 在主程式中引入模組
4. 確保模組存在(sys.path)中任一路徑,python才能找到
5. 否則需要增加 path list 或是 指定模組位置
```python=
#main.py
import sys
sys.path.append ( "module" ) #搜尋列表加入新的路徑列表(module為相對路徑)
print ( sys.platform ) #印出作業系統
print ( sys.maxsize ) #印出整數型態的最大值
import module.geometry as geometry #指定模組位置
result = geometry.distance( 1,1,5,5 )
print ( result )
result = geometry.slope( 1,2,5,6 )
print ( result )
print ( sys.path )
```
```python=
#geometry.py
def distance ( x1, y1, x2, y2 ):
#兩點距離
return (( x2 - x1 ) ** 2 + ( y2 - y1 ) ** 2) ** 0.5
def slope ( x1, y1, x2, y2 ):
#兩點斜率
return (y2 - y1) / ( x2 - x1 )
```
## 封包 Package
* 用來整理、分配模組程式
* 可以很多層
### 建立封包
1. 建立封包資料夾
2. 加入(__init__.py)內容可以留空
3. 可自行建立其他細部資料夾
### 基本語法
```python=
#main.py
import geometry.point
result = geometry.point.distance (3,4)
print ( result )
import geometry.point as gp
result = gp.distance (3,4)
print ( result )
import geometry.line
result = geometry.line.lenth (3,4,5,6)
print ( "len : ", result )
result = geometry.line.slope (3,4,5,6)
print ( "slope : ", result )
import geometry.line as gl
result = gl.lenth (3,4,5,6)
print ( "len : ", result )
result = gl.slope (3,4,5,6)
print ( "slope : ", result )
```
```python=
#line.py
def distance ( x, y ):
return ((x ** 2) + (y ** 2)) ** 0.5
```
```python=
#point.py
def lenth ( x1, y1, x2, y2 ):
return (( x2 - x1 ) ** 2 + ( y2 - y1 ) ** 2) ** 0.5
def slope ( x1, y1, x2, y2 ):
return (y2 - y1) / ( x2 - x1 )
```