# Python Shell & \_\_repr\_\_
時常看到 pyhon 文件的 Example Code 是入一行程式碼,下一行會立刻輸出結果。然而我們平常使用 IDE (Integrated Development Environment) 或由 Terminal (終端機,即 windows 的 CMD) 執行 Python File 卻不是這個方式,其實 pyhon 文件是執行在直譯器 (python shell) 的結果。
## 如何執行 Python Shell
> 於 Terminal 輸入「Python」即可進入 python shell,並且按下組合鍵「ctrl+Z」就能退出 python shell (於 Windows 作業系統)
## SyntaxError: invalid syntax、File \"\<stdin\>\"\, line 1
> 此訊息通常是你嘗試於 shell 執行 python file,但是直譯器是不能這麼做的。正常程序是由 Terminal 執行 python file,Terminal 再將程式碼餵給 Shell。所以直譯器只能直接輸入程式碼,而不能拿來執行檔案。
## \_\_str\_\_ 與 \_\_repr\_\_
* 你知道 python 的物件 (object) 可以==直接用 object 的名字**回傳客製化的訊息或變數值**== 嗎?
* 例如:
```python=
clustering = DBSCAN(eps=3, min_samples=2).fit(X)
print(clustering) # 回傳 str type 的「DBSCAN(eps=3, min_samples=2)」
```
* 上述程式碼是用 class DBSCAN 生成一個 clustering 物件,有趣的是範例 code ==**直接輸入物件名稱** clustering 就能返回參數訊息==<br>
* 來源:[Python sklearn 模組中的 DBSCAN模組](https://scikit-learn.org/stable/modules/generated/sklearn.cluster.DBSCAN.html)
* 這與 override (覆寫) \_\_str\_\_ 與 \_\_repr\_\_ 有關
* 在 python 中若要建立類別 (class),最一般的語法是:
```python=
class test:
def __init__(self, A, B):
self.A = A
self.B = B
# 生成 test 類別的物件 obj
obj = test(100, 200)
```
* 直接於 IDE 執行 **print(obj)** 會看到:
> \<\_\_main\_\_.test object at 0x036EF7C0\>
* 題外話,直接於 IDE 執行 **obj** 會得到:
> "什麼也沒有發生"<br><br>
這是因為 IDE、Terminal 執行時是讓直譯器讀取 obj,並不會把返還值回傳出來。<br><br>除非是使用 python shell 輸入 obj 才會看到:<br>
> \<\_\_main\_\_.test object at 0x036EF7C0\>
* 但預設的返還值對我們來說沒有意義,若想要**實現** sklearn 文件中 ==「輸入 object 直接返還自訂訊息或變數值」這種高端操作==,可以這麼寫:
```python=
class Test:
def __init__(self, A, B):
self.A = A
self.B = B
def __str__(self): # print
return 'use str'
def __repr__(self): # Shell
return 'use repr'
obj = test(100, 200)
```
* 直接覆寫 \_\_str\_\_ 和 \_\_repr\_\_ 都可以達到這個目的,差別在於系統預設的**優先順序** 與 **使用時機**;<br>對於指令 **print(object)** 而言,程式套用的優先序位是: \_\_str\_\_ \> \_\_repr\_\_;<br>**shell** 直接輸入 object 名字則是精準套用 \_\_repr\_\_
* 於 IDE、Terminal,若照上述同時覆寫 \_\_str\_\_ 和 \_\_repr\_\_ 則:
```python=
print(obj)
# 顯示:use str
obj
# "沒有任何反應"
```
* 於 IDE、Terminal,若**只有覆寫其中一種:
```python=
# 只覆寫 __str__
print(obj)
# 顯示:use str
```
```python=
# 只覆寫 __repr__
print(obj)
# 顯示:use repr
```
* 於 shell
```python=
>>> print(obj)
```
> 返還:use str
```python=
>>> obj
```
> 返還:use repr
###### tags: `Code` `Python` `invalid syntax`