The Python Data Model

1. A Pythonic Card Deck

It demonstrates the power of implementing just two special methods, __getitem__ and __len__.

A deck as a sequence of playing cards.

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]

 

The use of collections.namedtuple to construct a simple class to represent individual cards.We use namedtuple to build classes of objects that are just bundles of attributes with no custom methods, like a database record.

2.How Special Methods Are Used

3.Collection API

Each of the top ABCs has a single special method. The Collection ABC (new in Python 3.6) unifies the three essential interfaces that every collection should implement:

 • Iterable to support for, unpacking, and other forms of iteration

• Sized to support the len built-in function
• Container to support the in operator

Python does not require concrete classes to actually inherit from any of these ABCs. Any class that implements __len__ satisfies the Sized interface.

Three very important specializations of Collection are:

  • Sequence, formalizing the interface of built-ins like list and str

  • Mapping, implemented by dict, collections.defaultdict, etc.

  • Set, the interface of the set and frozenset built-in types

    Only Sequence is Reversible, because sequences support arbitrary ordering of their contents, while mappings and sets do not.

4. Overview of Special Methods

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值