利用collections.namedtuple 快速生成类python
import collections Card = collections.namedtuple('Card', ['rank', 'suit']) class FrenchDeck: ranks = [str(n) for n in range(2, 11)] + list('JQKA') 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() >>> deck[0] Card(rank='2', suit='spades') >>> deck[-1] Card(rank='A', suit='hearts')
若是my_object 是一个自定义类的对象,那么 Python 会本身去调用其中由 你实现的 len 方法。
Python 内置的类型,好比列表(list)、字符串(str)、 字节序列(bytearray)等,那么 CPython
会抄个近路,__len__ 实际 上会直接返回 PyVarObject 里的 ob_size 属性。程序员
for i in x: 这个语句
背后其实用的是 iter(x)
而这个函数的背后则是 x.__iter__() 方法。dom
好比 foo 之类的
由于虽然如今这个名字没有被 Python 内部使用,之后就不必定了函数
一个轮子 随机抽牌ui
>>> from random import choice >>> choice(deck) Card(rank='3', suit='hearts') >>> choice(deck) Card(rank='K', suit='spades') >>> choice(deck) Card(rank='2', suit='clubs')