類別結構:屬性與方法

Python 物件導向程式設計

Alex Yarosh

Content Quality Analyst @ DataCamp

基本類別

class Customer:

# code for class goes here
pass
  • class <name>: 開始定義類別
  • class 內的程式碼需縮排
  • pass 建立「空的」類別
c1 = Customer()
c2 = Customer()
  • ClassName() 建立 ClassName 的物件
Python 物件導向程式設計

為類別加入方法

class Customer:  

    def identify(self, name):   
      print("I am Customer " + name)
  • 方法定義=類別中的函式定義
  • 方法定義的第 1 個引數用 self
cust = Customer()
cust.identify("Laura")
I am Customer Laura
  • 從物件呼叫方法時可忽略 self
Python 物件導向程式設計
class Customer:  

    def identify(self, name):   
      print("I am Customer " + name)

cust = Customer()
cust.identify("Laura")

什麼是 self?

  • 類別是範本,如何指向特定物件的資料?
  • self 是在類別定義中代表特定物件的替身
  • 應該是所有方法的第一個引數
  • 從物件呼叫方法時,Python 會自動處理 self

cust.identify("Laura") 會被解讀為 Customer.identify(cust, "Laura")

Python 物件導向程式設計

我們需要屬性

  • 封裝:將資料與操作該資料的方法綁在一起
  • 例如 Customer 的名字應該是屬性

  $$\text{\Large{屬性在方法中以賦值(=)建立}}$$

Python 物件導向程式設計

為類別加入屬性

class Customer:  
    # set the name attribute of an object to new_name
    def set_name(self, new_name):

# Create an attribute by assigning a value self.name = new_name # <-- will create .name when set_name is called
cust = Customer()                   # <--.name doesn't exist here yet

cust.set_name("Lara de Silva") # <--.name is created and set to "Lara de Silva"
print(cust.name) # <--.name can be used
Lara de Silva
Python 物件導向程式設計

舊版本

class Customer:  



    # Using a parameter
    def identify(self, name):   
      print("I am Customer" + name)
cust = Customer()

cust.identify("Eris Odoro")
I am Customer Eris Odoro

新版本

class Customer:  
   def set_name(self, new_name): 
      self.name = new_name

    # Using .name from the object it*self*
    def identify(self):     
      print("I am Customer" + self.name)
cust = Customer()
cust.set_name("Rashid Volkov")
cust.identify()
I am Customer Rashid Volkov
Python 物件導向程式設計

一起來練習吧!

Python 物件導向程式設計

Preparing Video For Download...