zoukankan      html  css  js  c++  java
  • python面对对象编程------3:写集合类的三种方法

    写一个集合类的三种方法:wrap,extend,invent

    一:包装一个集合类

    class Deck:
    def __init__( self ):
    self._cards = [card6(r+1,s) for r in range(13) for s in (Club,Diamond, Heart, Spade)] #这就是受包装的list型数据,添加方法对其进行操作
    random.shuffle( self._cards )

    def pop( self ):
    return self._cards.pop()  #直接调用list的pop方法

    d= Deck()
    hand = [ d.pop(), d.pop() ] #包装类,通过init初始数据,通过方法对其进行操作,若集合特别大而操作特别复杂时会使此类写起来十分繁琐。



    二:继承一个已有的集合类,此例继承list,可以直接把下列中的self看作list进行处理,好处在于有很多方法不用自己写了
    class Deck2( list ): #有些时候需要重写一些方法来达到更贴切的效果
    def __init__( self ):
    super().__init__( card6(r+1,s) for r in range(13) for s in (Club, Diamond, Heart, Spade) )
    random.shuffle( self )

    当有更多要求时,需要做一些自定义
    class Deck3(list): #有些纸牌游戏需要多副牌才能够完成游戏,decks表示需要的副数,而一次要发多张牌出去
    def __init__(self, decks=1):
    super().__init__()
    for i in range(decks):
    self.extend( card6(r+1,s) for r in range(13) for s in (Club, Diamond, Heart, Spade) ) #注意此地extend用法

    random.shuffle( self )
    burn= random.randint(1,52)
    for i in range(burn):
    self.pop()

    三:自行创建

    一般用不到,而且很繁琐,有许多特殊方法需要实现

  • 相关阅读:
    python程序设计练习题:电子银行购物商城
    python -m参数
    Python 中的 if __name__ == 'main' 的作用和原理
    Modbus协议
    Python configparser模块
    Python logging 模块:日志处理
    python hashlib模块
    Python time模块:Python 日期和时间
    mac 使用系统的自带的quickTime录屏
    Linphone android3.2.4 采用率设置(模拟电话大网信道)
  • 原文地址:https://www.cnblogs.com/pengsixiong/p/5381522.html
Copyright © 2011-2022 走看看