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 exercise below and ask your questions.

Ex2: Number Class

1     class Number:
2             def __init__(self, num, obj_name):
3                     self.num = num
4                     self.obj = obj_name
5     a = Number(5, 'a')
6     b = Number(-4, 'b')

Based on this class create a Number that behaves like an int class, but with the extra parameter of putting in a variable name. The class should at least be able to be added, substracted, multiplied and divided.