類別剖析:__init__ 建構子

Python 物件導向程式設計

Alex Yarosh

Content Quality Analyst @ 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 物件導向程式設計

建構子

  • 建立物件時就加入資料嗎?
  • 每次建立物件都會呼叫「建構子」 __init__() 方法。
class Customer:
       def __init__(self, name):     
        self.name = name           # <--- Create the .name attribute and set it to name parameter
        print("The __init__ method was called")

cust = Customer("Lara de Silva") #<--- __init__ is implicitly called print(cust.name)
The __init__ method was called
Lara de Silva
Python 物件導向程式設計
class Customer:
       def __init__(self, name, balance):  # <-- balance parameter added

self.name = name self.balance = balance # <-- balance attribute added print("The __init__ method was called")
cust = Customer("Lara de Silva", 1000) # <-- __init__ is called print(cust.name) print(cust.balance)
The __init__ method was called
Lara de Silva
1000
Python 物件導向程式設計
class Customer:
       def __init__(self, name, balance=0):  #<--set default value for balance

self.name = name self.balance = balance print("The __init__ method was called")
cust = Customer("Lara de Silva") # <-- don't specify balance explicitly
print(cust.name) print(cust.balance) # <-- attribute is created anyway
The __init__ method was called
Lara de Silva
0
Python 物件導向程式設計

方法中建立屬性

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

    def my_method2(self, attr2):        
        self.attr2 = attr2
        ...
obj = MyClass()
obj.my_method1(val1) # <-- attr1 created
obj.my_method2(val2) # <-- attr2 created

在建構子中建立屬性

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

# All attributes are created obj = MyClass(val1, val2)
  • 輕鬆掌握所有屬性
  • 物件建立時就建立屬性
  • 讓程式碼更好用、易維護
Python 物件導向程式設計

最佳實務

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

最佳實務

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

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

Python 物件導向程式設計

最佳實務

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

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

3. 保持 self 就是 self
class MyClass:
    # This works but isn't recommended
    def my_method(kitty, attr):
       kitty.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...