# 定義類別

``class Account:    passdef deposit(acct, amount):    if amount <= 0:        raise ValueError('must be positive')    acct.balance += amount       def withdraw(acct, amount):    if amount <= acct.balance:        acct.balance -= amount    else:        raise RuntimeError('balance not enough')        acct = Account()acct.number = '123-456-789'acct.name = 'Justin'acct.balance = 0print(acct.number)    # 123-456-789print(acct.name)      # Justindeposit(acct, 100)print(acct.balance)   # 100withdraw(acct, 50)print(acct.balance)   # 50``

``class Account:    def __init__(self, number, name):        self.number = number        self.name = name        self.balance = 0            def deposit(self, amount):        if amount <= 0:            raise ValueError('must be positive')        self.balance += amount            def withdraw(self, amount):        if amount <= self.balance:            self.balance -= amount        else:            raise RuntimeError('balance not enough')``

def __init__(self, number, name):
self.number = number
self.name = name
self.balance = 0

__init__這個特定的名稱，用來定義類別的實例建立之後，要進行的初始化動作。第一個self參數代表建立的類別實例，在Python中，實例可操作的方法，第一個參數必須明確作為接受實例之用，慣例上取名為self名稱。__init__之後則可指定初始化時所必須給定的資料。在上面的例子中，會在建立的實例上增加number、name與balance特性。你可以用以下方式來建構物件：
acct = Account('123-456-789', 'Justin')

print(acct.number)    # 123-456-789
print(acct.name)      # Justin

def deposit(self, amount):
if amount <= 0:
raise ValueError('must be positive')
self.balance += amount

def withdraw(self, amount):
if amount <= self.balance:
self.balance -= amount
else:
raise RuntimeError('balance not enough')

acct.deposit(100)
print(acct.balance)   # 100
acct.withdraw(50)
print(acct.balance)   # 50

acct1 = Account('123-456-789', 'Justin')
deposit1 = acct1.deposit
withdraw1 = acct1.withdraw
deposit1(100)
withdraw1(50)
print(acct1.balance)

acct2 = Account('987-654-321', 'Momor')
deposit2 = acct2.deposit
withdraw2 = acct2.withdraw
deposit2(200)
withdraw2(100)
print(acct2.balance)

acct1.deposit = acct2.deposit
acct1.deposit(1000)      # 你其實是將錢存到 acct2 去
print(acct1.balance)     # 50
print(acct2.balance)     # 1100