標籤:other int 分享 font 父類 sel img meta static
一、abstractmethod
- 子類必須全部實現重寫父類的abstractmethod方法
- 非abstractmethod方法可以不實現重寫
- 帶abstractmethod方法的類不能執行個體化
from abc import abstractmethod, ABCMeta
1 class BettingStrategy(metaclass=ABCMeta): 2 3 @abstractmethod 4 def bet(self): 5 print(‘0‘) 6 7 def record_win(self): 8 print(‘win‘) 9 10 def record_loss(self):11 print(‘loss‘)12 13 14 class Bet(BettingStrategy):15 def bet(self):16 print(‘1‘)
擴充:abc模組
二、staticmethod:靜態函數
對象不用執行個體化即可調用的函數
1 class Hand4: 2 def __init__(self, dealer_card, *cards): 3 self.dealer_card = dealer_card 4 self.cards = cards 5 6 @staticmethod 7 def freeze(other): 8 hand = Hand4(other.dealer_card, *other.cards) 9 return hand10 11 @staticmethod12 def split(other, card0, card1):13 hand0 = Hand4(other.dealer_card, other.cards[0], card0)14 hand1 = Hand4(other.dealer_card, other.cards[1], card1)15 return hand0, hand116 17 def __str__(self):18 return ‘,‘.join(map(str, self.cards))
1 h41 = Hand4(deck3.pop(), deck3.pop(), deck3.pop())2 s1, s2 = Hand4.split(h41, deck3.pop(), deck3.pop())3 s3 = Hand4.freeze(h41)
調用
Python物件導向編程——一些類定義(雜)