Extending a collection class

An alternative to wrapping is to extend a built-in class. By doing this, we have the advantage of not having to reimplement the pop() method; we can simply inherit it.

The pop() method has an advantage in that it creates a class without writing too much code. In this example, extending the list class has the disadvantage that this provides many more functions than we truly need.

The following is a definition of Deck2 that extends the built-in list object:

class Deck2(list):

def __init__(self) -> None:
super().__init__(
card(r + 1, s)
for r in range(13) for s in iter(Suit))
random.shuffle(self)

In this case, we've initialized the list with Card instances. super().__init__() reaches up to the superclass initialization to populate our list object with an initial single deck of cards. After seeding the list, the initializer then shuffles the cards. The pop() method is directly inherited from list and works perfectly. Other methods inherited from the list class will also work.

While simpler, this exposes methods such as delete() and remove(). If these additional features are undesirable, a wrapped object might be a better idea.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset