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
- What Does It Take To Be An Expert At Python?
This is a talk about expert python programming and this is what we will cover the rest of this semester. (Todays topic is from the beginning to 18:43)
Expert Python Tutorial #2 - Dunder/Magic Methods & The Python Data Model
Exercises
Ex1: Deck of cards
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.