[Tutor] access class through indexing?

Evert Rol evert.rol at gmail.com
Wed Aug 4 22:31:20 CEST 2010


> Hi all,
> Further to my questions about overriding builtin methods earlier, how
> would I make a class able to be accessed and changed using index
> notation? For example, take the following:
> deck=CardPile(52) #creates a new deck of cards
> print(len(deck)) #prints 52, thanks to my __len__ function
> for c in deck: print c #also works thanks to __iter__
> print(deck[4]) #fails with a list index out of range error
> How would I get the last one working? I tried __getattr__(self, i),
> but it did not work. I want to be able to get an arbitrary item from
> the "pile" of cards (which can be a deck, a hand, whatever), and/or
> set an element. A "pile" is just a list of Card objects, so I would
> only need to use sequence indexing, not mapping functions.

If you want most or all of the things that lists implement, and you feel in general that CardPile is really an advanced/augmented list, just let CardPile inherit from list: class CardPile(list).
I would think that should work for what you want.

  Evert




More information about the Tutor mailing list