類別剖析:屬性與方法

Python 物件導向程式設計入門

George Boorman

Curriculum Manager, DataCamp

一個 Customer 類別

class Customer:

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

為類別加入方法

class Customer:  

def identify(self, name): print("I am Customer " + name)
  • 方法定義=類別中的函式定義
  • 在方法定義中將 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 應該是所有方法的第一個參數
  • self 代表(尚未建立的)物件
  • cust.identify("Laura") 會被解讀為 Customer.identify(cust, "Laura")
Python 物件導向程式設計入門

我們需要屬性

  • OOP 將資料與操作資料的方法打包
    • 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 # Will create .name when set_name is called self.name = new_name
# Create an object # .name doesn't exist here yet cust = Customer()
# .name is created and set to "Lara de Silva" cust.set_name("Lara de Silva")
print(cust.name)
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...