流畅的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])
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])
相关文章推荐
- 流畅的python学习笔记:第三章
- 流畅的python学习笔记第八章:深拷贝,浅拷贝,可变参数
- 流畅python学习笔记:第十九章:动态属性和特性
- 流畅python学习笔记第十八章:使用asyncio编写服务器
- 流畅的python学习笔记第一篇之为什么要学习这本书
- 流畅python学习笔记第十八章:使用asyncio包处理并发(一)
- 流畅的python学习笔记:第九章:符合python风格的对象
- 流畅的python学习笔记:第一章
- 流畅python学习笔记:第十九章:动态属性和特性
- 流畅的python学习笔记:第十三章:重载运算符__add__,__iadd__,__radd__,__mul__,__rmul__,__neg__,__eq__,__invert__,__pos__
- 流畅python学习笔记第十八章:使用asyncio包处理并发(二)
- 流畅python学习笔记:第十四章:迭代器和生成器
- 流畅python学习笔记:第十六章:协程
- 流畅python学习笔记:第十七章:并发处理
- 流畅python学习笔记:第十二章:子类化内置类型
- 流畅的python学习笔记:第二章
- 流畅的python学习笔记:第五章
- 流畅python学习笔记:第十五章:上下文管理器
- 流畅python学习笔记:第十七章:并发处理二
- 流畅的python学习笔记:第十一章:抽象基类