Python Classroom Series – 07/Oct/2020

Python Data Model

  • Basic Mantra of Python Everything in Python is an Object
  • Think of Python Data Model as description of Python as a framework
  • Python interpreter invokes special methods (dunder) methods to perform basic object operations
  • Lets use two special methods (dunder) dunder getitem and dunder len __getitem__ and __len__ to implement Card deck Refer Here
import collections

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

class FrenchDeck:
    This class will create a french deck
    ranks = [str(n) for n in range(2,11)] + list('JQKA')
    suits = 'spades diamonds clubs hearts'.split()

    def __init__(self):
        Initializing the french deck
        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]

  • Special Method names: Preview

  • Special Method names for operators Preview

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.

About learningthoughtsadmin