Python物件導向編程——一些類定義(雜)

來源:互聯網
上載者:User

標籤: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物件導向編程——一些類定義(雜)

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.