Classes and Objects

For the purposes of this course, feel free to skip this section (and come back later) if it doesn't make sense! You will rarely have to define your own classes in mathematical computing, but it's useful in enterprise applications.

In object-oriented programming, a class is a template for creating objects of a certain type. Instances are objects created using this template. For example, a Polynomial class would be the textbook definition of a polynomial, while $x^2 + 3x + 5$ would be an instance of a Polynomial.

An example class

We can create classes in Python in the following manner:

Creating a class

Classes have only two required elements: a name and a body. The name is arbitrary - it will be used to refer to instances.

Constructors are called when an object is created - in the example above, Nothing() is the call to the constructor. They are used to initialize instance variables and prepare the object for use. In Python, they are declared as the __init__ function.

A no-argument, do-nothing constructor is provided by default, but it's often useful to define your own:

Instance variables

We call coefficients an instance variable because a different value is associated with each instance:

Instance methods

Instance methods operate on the instance variables in the class, updating the instance variables (the internal state) and possibly returning some information. They can be spotted by their first argument being self (by convention).

Static/class methods

Static methods and class methods don't operate on particular objects; they cannot access instance variables.

Inheritance

Python supports (multiple) inheritance. This is used when functionality for a general object should be reused for particular types of that object. In this example, Polynomial is the superclass and Quadratic (the subclass) is inheriting from it.