1. 程式人生 > >Python面向對象編程——一些類定義(雜)

Python面向對象編程——一些類定義(雜)

pytho 面向 子類 圖片 aps clas color dea bstr

一、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 hand 10 11 @staticmethod 12 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, hand1 16 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面向對象編程——一些類定義(雜)