# 4/09 Python與資料分析#5 - 物件 Procedural Programming 線性、單方向走向的程式設計 Object-oriented Programming 比較沒有順序性、同心圓向外擴展 ## 物件Object與類別Class ### 物件 由某個類別宣告出來的變數名稱,具備該類別某種行為特徵 They hold both data, and ways to manipulate the data. ### 類別 提供這個物件需要的行為,而宣告出來的東西 A class provides a set of behaviors in the form of member functions (also known as methods) 可以視為"物件"的"藍圖",使用上可以稍做修改 A class also serves as a blueprint for its instances 物件就是實踐類別這個藍圖的產品 例如類別list有pop的行為 字串str有迭代的行為 ### 一些內建的類別 * Scalars int float str bool NoneType * Data Structures list tuple dict set * 第三方開發 ndarray Index Series DataFrame ## 建構Class 將特定函數或資料綁在某個物件上 ### 綁定特定函數(方法) * class defines the name diplayed when calling type() after object is created * __init__ initiates the object itself * self proxies the object itself after object is created ``` class ClassName: #Class 類別名稱 """ docstring: print documentation when __doc__ attribute is accessed """ def __init__(self, ATTRIBUTES, ...): # sequence of statements 綁定資料 # 可以看做起始呼叫的某個叫__init__的函數 def method(self, ATTRIBUTES, ...): # sequence of statements 綁定函數 ``` 舉例 定義甚麼都沒做的類別 ``` class SimpleCalculator: """ This class creates a simple calculator that is unable to do anything. """ pass ``` 物件化 ``` sc = SimpleCalculator() print(type(sc)) print(sc.__doc__) ``` 得到: <class '__main__.SimpleCalculator'> This class creates a simple calculator that is unable to do anything. 另一個例子: ``` class SimpleCalculator: """ This class creates a simple calculator that is able to add and subtract 2 numbers. """ def add(self, x, y): return x + y def subtract(self, x, y): return x - y ``` 呼叫使用的時候 ``` sc = SimpleCalculator() sc.add('55', '66') sc.subtract(55, 66) ``` 後來將此類別命名成sc 呼叫的時候要sc.add self可以想成代名後來命名的sc class SimpleCalculator 類似generator sc實體化 有些操作不是函數名稱() 而是 資料名稱.操作方式 例如x.append而非append(x) 就是因為把append視為class下的一個方法 ### 綁定特定資料(屬性attributes) 使用__init()__ 舉例 ``` class SimpleCalculator: """ This class creates a simple calculator that is able to add, subtract, multiply, and divide 2 numbers. This class has an attribute of Euler's number: e. """ def __init__(self): self.e = 2.71828182846 ``` 把e=2.718...用在此物件下,用self代替這個類別的名稱 使用的話就用self.e代替這個資料 ## 繼承 Inheritance class 新的類別名稱(想要拿來用的已經定義的類別名稱): pass 就可以繼承之前的類別了 使用的時候會用新的類別名稱 例如sc=新的名稱() sc.函數名稱 連同之前的屬性也可以用 也可以在後面def新的方法 許多東西可以延用之前的東西,不需要自己重新做 ###### tags: `python` `資料分析`