Example classes

Martin McBride, 2019-01-01
Categories magic methods
In section Python language

To illustrate magic methods, we will use a couple of simple user defined classes as examples. These will be extended by adding magic methods in the remaining articles.

The Person class

Here is a simple Person class:

class Person:

def __init__(self, title, forename, surname):
self.title = title
self.forename = forename
self.surname = surname


This class simply holds the person's title, forename and surname as string fields.

The Matrix class

We will define a class that holds the values for a 2 by 2 matrix

$$\begin{pmatrix}a & b\\c & d\end{pmatrix}$$

Here is the simple Matrix class:

class Matrix:

def __init__(self, a, b, c, d):
self.data = [a, b, c, d]


If you found this article useful, you might be interested in the book Functional Programming in Python, or other books, by the same author.

<<Prev