類別結構:__init__ 建構子

Python 物件導向程式設計入門

George Boorman

Curriculum Manager, DataCamp

方法與屬性

  • 方法是類別內的函式定義
  • 第一個引數為 self
  • 以指定建立屬性
  • 在類別中用 self.___ 參照屬性
  • 呼叫太多方法會變得難以維護!
class MyClass:
    # function definition in class
    # first argument is self
    def my_method1(self, other_args...):
        # do things here

def my_method2(self, my_attr): # attribute created by assignment self.my_attr = my_attr ...
Python 物件導向程式設計入門

建構子(Constructor)

  • 物件建立時加入資料
  • 物件每次被建立都會呼叫「建構子」 __init__() 方法
    • __methodname__ 語法而自動呼叫
class Customer:
    def __init__(self, name):
        # 建立 .name 屬性並設為參數 name
        self.name = name
        print("The __init__ method was called")
Python 物件導向程式設計入門

建構子(Constructor)

# __init__ 會被隱式呼叫 
cust = Customer("Lara de Silva")   
print(cust.name)
The __init__ method was called
Lara de Silva
Python 物件導向程式設計入門

在方法中建立屬性

class MyClass:
    def my_method1(self, attr1):
        self.attr1 = attr1
        ...

    def my_method2(self, attr2):        
        self.attr2 = attr2
        ...

obj = MyClass() # 建立 attr1 obj.my_method1(val1) # 建立 attr2 obj.my_method2(val2)

在建構子中建立屬性

class MyClass:
    def __init__(self, attr1, attr2):
        self.attr1 = attr1
        self.attr2 = attr2
        ...

# 一次建立所有屬性 obj = MyClass(val1, val2)
  • 一般來說應使用建構子
  • 物件建立時就建立屬性
  • 更好用、也更易維護的程式碼
Python 物件導向程式設計入門

加入引數

class Customer:
    # 加入 balance 引數
    def __init__(self, name, balance): 

self.name = name # 加入 balance 屬性 self.balance = balance print("The __init__ method was called")
Python 物件導向程式設計入門

加入參數

# __init__ 被呼叫
cust = Customer("Lara de Silva", 1000)
print(cust.name)
print(cust.balance)
The __init__ method was called
Lara de Silva
1000
Python 物件導向程式設計入門

預設引數

class Customer:
    # 為 balance 設定預設值
    def __init__(self, name, balance=0):
        self.name = name
        # 指定新屬性
        self.balance = balance
        print("The __init__ method was called")
Python 物件導向程式設計入門

預設引數

# 不需明確指定 balance
cust = Customer("Lara de Silva")

print(cust.name) # balance 屬性仍會被建立 print(cust.balance)
The __init__ method was called
Lara de Silva
0
Python 物件導向程式設計入門

最佳實務

1. 在 __init__() 初始化屬性
Python 物件導向程式設計入門

最佳實務

1. 在 __init__() 初始化屬性
2. 命名

類別用 CamelCase,函式與屬性用 lower_snake_case

Python 物件導向程式設計入門

最佳實務

1. 在 __init__() 初始化屬性
2. 命名

類別用 CamelCase,函式與屬性用 lower_snake_case

3. 保持 selfself
class MyClass:
    # 這樣可行,但不建議
    def my_method(george, attr):
        george.attr = attr
Python 物件導向程式設計入門

最佳實務

1. 在 __init__() 初始化屬性
2. 命名

類別用 CamelCase,函式與屬性用 lower_snake_case

3. self 就是 self
4. 使用 docstring
class MyClass:
    """This class does nothing"""
    pass
Python 物件導向程式設計入門

一起來練習吧!

Python 物件導向程式設計入門

Preparing Video For Download...