---
# System prepended metadata

title: Python 2021_11_23
tags: [Python]

---

---
tags: Python
title: 'Python 2021_11_23'
disqus: hackmd

---

[TOC]


---
---

Python Learning
===

## Table of Contents
[TOC]

## 修改檔案的方法(just for 文字檔)

一、修改原檔案方式
```python=
def alter(file,old_str,new_str): 
#file：檔名
#old_str：要被替換的字串
#new_str：替換的字串
    with open(file,"r",encoding="utf-8") as f1,
    open( filename, "w",encoding="utf-8") as f2:
      for line in f1:
        if old_str in line:
            line = line.replace(old_str,new_str)
        f2.write(line)
    os.remove(file_path) #也可以不刪除
    os.rename( filename, filename)

alter(file_path,"(Dx, Dy, Dz)",new_str)

```
## 有視窗介面可選擇file
```python=
import tkinter as tk
from tkinter import filedialog

root = tk.Tk()    
root.withdraw()   

print("you want to cover file：")
file_path = filedialog.askopenfilename(parent=root)
```

## 物件導向概念
[Python物件導向](https://www.learncodewithmike.com/2020/01/python-class.html)
* 類別(Class)
* 物件(Object)
* 屬性(Attribute)
* 建構式(Constructor)
* 方法(Method)

```pyrhon
# motorcycle type
class Motorcycle:
    pass

# car type
class Car:
    #建構式
    
    def __init__(self, color, seat):
        self.color = color #顏色屬性
        self.seat = seat   #座位屬性
        
    #方法(method)
    def drive(self):
        print(f"My car is {self.color} and {self.seat} seats.")

    #object_name = classname()
    pass

#toyota = Car()         #建立 Car 類別的物件
toyota = Car("blue",4)  #建立 Car 類別的物件

#檢查物件導向 isinstance(object_name, class_name)
print(isinstance(toyota, Car))         # 執行結果：True
print(isinstance(toyota, Motorcycle))  # 執行結果：False

toyota.color = "blue" #顏色屬性 給定value
toyota.seat = 4       #座位屬性 給定value

print(toyota.color)  # 執行結果：blue
print(toyota.seat)  # 執行結果：4

toyota.drive()
```


## python module

[解析Python模組(Module)和套件(Package)的概念](https://www.learncodewithmike.com/2020/01/python-module-and-package.html)
1. 把所有用得到function的py檔放在同一個路徑裡
1. 路徑裡要有**vs**、**vscode**的資料夾
2. run完專案後，會產生**pycache**的資料夾
3. **pycache**資料夾中，可以看到包含了引用模組的已編譯檔案，當下一次執行主程式時，Python編譯器看到已編譯的模組檔案，會直接載入該模組(Module)，而省略編譯的動作，藉此來加速載入模組(Module)的速度。

以主程式裡用了兩個模組為例：
主程式: app.py
副程式: post.py、about.py

### about.py
```python=
#取得作者
def get_author():
    return "Mike"

#取得電子郵件
def get_email():
    return "learncodewithmike@gmail.com"
```

### post.py
```python=
class Post:

    # 建構式
    def __init__(self):
        self.titles = []

    # 新增文章
    def add_post(self, title):
        self.titles.append(title)

    # 刪除文章
    def delete_post(self, title):
        self.titles.remove(title)
    pass
```


### app.py
```python=
from post import Post
from about import get_author, get_email

p = Post()
p.add_post("Python Programming")
author = get_author()
email = get_email()
print(p.titles)  #執行結果：['Python Programming']
print(author)  #執行結果：Mike
print(email)  #執行結果：learncodewithmike@gmail.com


```
## python package

新增一個資料夾(blog)把有function 的 py檔放進去
新增的資料夾裡面要有__init__.py (可以是空的)
只要以後要import時就用以下：
```python=
from blog import post
from blog import about
```
但切記之後的寫法就會變成：
```python=
p = post.Post()
p.add_post("myprogram")
author = about.get_author()
email = about.get_email()
```