您的位置:首页 > 编程语言 > Python开发

流畅的python学习笔记

2017-06-12 22:38 363 查看
1.1 一摞python风格的纸牌

import collections

Card=collections.namedtuple('Card',['rank','suit'])

class FrenchDeck:

    ranks=[str(n) for n in range(2,11)]+list('JQKA')

#     print(ranks)

    suits='spades diamonds clubs hearts'.split()

    

    def __init__(self):

        self._cards=[Card(rank,suit)for suit in self.suits

                                    for rank in self.ranks ]

    def __len__(self):

        return len(self._cards)

    

    def __getitem__(self,position):

        return self._cards[position]

魔法方法可直接调用类里面的函数方法,实例如下:

deck=FrenchDeck()

print(len(deck))

print(deck[0])

print(deck[-1])

非魔法方法需调用类里面的函数方法,实例如下:

deck=FrenchDeck()

k=deck.len()

print(k)

from random import choice

print(choice(deck))

print(choice(deck))

print(choice(deck))

print(deck[:3])
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: