Python面向对象编程——一些类定义(杂)

一、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)
调用

 

posted @ 2018-07-22 09:22  Stranger115  阅读(131)  评论(0编辑  收藏  举报