## 2015年7月7日 星期二

### [Python 學習筆記] 函式、類別與模組 : 類別 (抽象類別)

Preface :

- 類別 Account :
1. class Account:
2.     def withdraw(self, amount):
3.         if amount <= self.balance:
4.             self.balance -= amount
5.         else:
6.             raise ValueError('Not enough balance')
7.
8.     def __str__(self):
9.         return ('Id:\t\t' + self.id +
10.                 '\nName:\t\t' + self.name +
11.                 '\nBalance:\t' + str(self.balance))

acct = Account()
print(acct)

Abstract Class :

- 類別 CheckingAccount :
1. class CheckingAccount(Account):
2.     def __init__(self, id, name):
3.         self.id = id
4.         self.name = name
5.         self.balance = 0
6.         self.overdraftlimit = 30000
7.
8.     def withdraw(self, amount):
9.         if amount <= self.balance + self.overdraftlimit:
10.             self.balance -= amount
11.         else:
12.             raise ValueError('Not enough credit')
13.
14.     def __str__(self):
15.         return (super(CheckingAccount, self).__str__()+
16.                 '\nOverdraft limit\t' + str(self.overdraftlimit))
17.
18. acct = CheckingAccount('E1223','Peter')
19. print(acct)

1. class Account:
2.     def __init__():
3.         raise NotImplementedError("Account is abstract")
4.
5.     ...略

----顯示訊息（提示使用者輸入）
----取得使用者輸入
----比較是否猜中
----顯示訊息（輸入正確與否）

- 類別 GuessGame :
1. import random
2. from abc import ABCMeta, abstractmethod
3.
4. class GuessGame(metaclass=ABCMeta):
5.     @abstractmethod
6.     def message(self, msg):
7.         pass
8.
9.     @abstractmethod
10.     def guess(self):
11.         pass
12.
13.     def go(self):
14.         self.message(self.welcome)
15.         number = int(random.random() * 10)
16.         while True:
17.             guess = self.guess();
18.             if guess > number:
19.                 self.message(self.bigger)
20.             elif guess < number:
21.                 self.message(self.smaller)
22.             else:
23.                 break
24.         self.message(self.correct)

- 類別 ConsoleGame :
1. class ConsoleGame(GuessGame):
2.     def __init__(self):
3.         self.welcome = "歡迎"
4.         self.prompt = "輸入數字："
5.         self.correct = "猜中了"
6.         self.bigger = "你猜的比較大"
7.         self.smaller = "你猜的比較小"
8.
9.     def message(self, msg):
10.         print(msg)
11.
12.     def guess(self):
13.         return int(input(self.prompt))

TypeError: Can't instantiate abstract class ConsoleGame with abstract methods message

1. import random
2. from abc import ABCMeta, abstractmethod
3.
4. class Flyer(metaclass=ABCMeta): # 就像是Java中的interface
5.     @abstractmethod
6.     def fly(self):
7.         pass
8.
9. class Bird:
10.     pass
11.
12. class Sparrow(Bird, Flyer):  # 就像Java中繼承Bird類別並實作Flyer介面
13.     def fly(self):
14.         print('麻雀飛')
15.
16. s = Sparrow()
17. s.fly()
Supplement
Python Standard Library: abc — Abstract Base Classes

### [ Python 文章收集 ] List Comprehensions and Generator Expressions

Source From  Here   Preface   Do you know the difference between the following syntax?  view plain copy to clipboard print ? [x  for ...