字牌游戏
先来看个扑克牌在代码中的可以的定义
from collections import namedtuple Card=namedtuple('Card_name',['rank','suit']) C1=Card(2,'red') print(C1)#Card_name(rank=2, suit='red') print(C1.rank)#2
再来来纸牌的代码
from collections import namedtuple Card=namedtuple('Card',['rank','suit']) class FranchDeck: ranks = [str(n) for n in range(2,11)] + list('JQKA') suits = ['红心','方板','梅花','黑桃'] def __init__(self): self.__cards = [Card(rank,suit) for rank in FranchDeck.ranks for suit in FranchDeck.suits] def __len__(self): return len(self.__cards)#list元素的个数 def __getitem__(self, item): return self.__cards[item] def __setitem__(self,key,value): self.__cards[key]=value deck = FranchDeck() print(len(deck._FranchDeck__cards))print(deck._FranchDeck__cards)print(deck.__dict__)print(deck[0])#调用了__getitem__print(deck[51])#调用了__getitem__ from random import choice print(choice(deck)) from random import shuffle shuffle(deck) print(deck.__dict__) print(deck[0]) print(deck[9])
解析:
choice函数需要用到__len__和__getiem__两个方法
首先调用__len__,方法得到一个返回值——数字,然后0——数字的范围随机去一个数字,然后填入__getitem__的方法中,的到的返回值,便是整的返回值了。如果报错,说明__getitem__
的代码写入有问题,不支持此函数的索引报错代码 '类名' object does not support indexing,即__getitem__不支持此 对象名[数字]这种的索引方式。
shuffle函数需要用用到__len__,__getitem__和__setitem__三个方法
首先调用len方法,拿到返回值,然后在把0到返回的数字带入get中,拿到key和value,只不过key是数字,然后把key和value的对应关系打乱,依次用set方法把key和value带入,便完成了重新
洗牌