# Python 模組
###### tags: `python`
[參考課程](https://www.youtube.com/watch?v=Et0DjY2cGiE&list=PL-g0fdC5RMboYEyt6QS2iLb_1m7QcgfHk&index=11)
引述:將程式寫在一個檔案中,此檔案可重複載入使用。
載入 > 使用
先載入模組,再使用模組中的函式或變數
## 基本語法
>import 模組名稱
>import 模組名稱 as 模組別名
## 使用模組
>模組名稱或別名.函式名稱(參數資料)
>模組名稱或別名.變數名稱
## 內建模組
sys
```python=
#載入sys模組 s為sys別名
import sys as s
#使用sys模組
print(s.platform)#印出作業系統
print(s.maxsize)#印出整數型態的最大值
print(s.path)#印出搜尋模組的路徑
```
## 自訂模組
把運算、操作等獨立到另一個檔案中
範例:
step1:建立幾何運算模組
建立檔案 geometry.py檔 定義平面幾何運算用的函式
step2:在主程式中載入與使用
**geometry.py檔**
```python=
#兩點距離
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)
```
**module.py檔**
```python=
import geometry
result = geometry.distance(1,1,5,5)
print("distance",result);
sl = geometry.slope(1,2,5,6)
print("slope",sl)
```
>distance 5.656854249492381
slope 1.0
## 模組路徑
### 搜尋模組路徑 --> sys.path
模組必須要放在此路徑中,才能被找到
### 管理模組
放在專門放模組資料夾,集中在一起
但預設的路徑可能不在新創的資料夾中
因此解決方法:e.g.新創modules
**在模組的搜尋列表中新增路徑**
**sys.path.append("modules")**
## 補充(路徑寫法):
>' / ':根目錄
' ./ ':當前同級目錄
' ../ ':上級目錄
#### 相對路徑
/ 表示相对路径
1. open('檔名1.txt')
2. open('/data/檔名2.txt')
3. open('./data/檔名3.txt')
4. open('../data/檔名4.txt')
#### 絕對路徑
\ 表示絕對路徑
open('C:\\user\\檔名5.txt')
# Python 封包的設計與使用
引述: 包含模組的資料夾,用來整理、分類模組的程式
## 專案檔案配置

如果沒有__init__.py則此資料夾不會被當封包來看待
__init__.py可以為空檔案
## 基本語法
>import 封包名稱.模組名稱
>import 封包名稱.模組名稱 as 模組別名
## 實作

**point.py檔**
```python=
def distance(x,y):
return (x**2+y**2)**0.5
```
**line.py檔**
```python=
def len(x1,y1,x2,y2):
return ((x2-x1)**2) + ((y2-y1)**2) **0.5
def slope(x1,y1,x2,y2):
return (y2-y1)/(x2-x1)
```
**main.py檔**
```python=
import geometry.point;
result = geometry.point.distance(3,4)
print("距離",result)
import geometry.line
reslut = geometry.line.slope(1,1,3,3)
print("斜率",result)
```