Session 9 - The python datamodel

Today we will look at the python datamodel.

Python has a protocol orientated datamodel.

After this you will be able to implement code in own classes that allow you to use pythons built-in functions or top level syntax to interact with these object.

Example:

If you want to be able to use the build in function len() on your object you should implement the __len__ method in your class.

If you want to be able to use the == operator on your object you should implement the __eq__ method in your class.

If you want to be able to use the in key word on your object you should implement the __contains__ method in your class.

Learning goals

  • Create your own classes, that behave like any other Python Object, and are able to interact with pythons build in functions or top level syntax.

Materials

Exercises

Ex1: Deck of cards

Solution

Continue with the deck example and implement the

  • __len__ method

  • __add__ method

  • __repr__ method

  • __str__ method

  • __setitem__ method

  • __delitem__ method

We look at this together in a short while.

When you a done, take a look at the 2 exercises below and ask your questions.