Home

Object Oriented Programming

We will take up one final example of classes in action. This is to demonstrate few important points about OOP along the way.

Vector: Mathematical Preliminaries

To each point P(x,y) in 2D space, we can associate what is called a vector. Geometrically, this is a directed arrow from the origin to the point P. That is, one tip of the vector will always be the origin and the other tip, also called the head of the vector, will be at the point P. Here, P1 and P2 are two vectors:

 

 

Some operations on vectors:

Magnitude

The magnitude of a vector P(x,y) is the length of the line segment OP:

|OP|=x2+y2

Scale

A vector can be scaled by a value s. Scaling modifies the length of the vector without changing the direction in which it is pointing at. This is equivalent to the following transformation:

s(x,y)(sx,sy)

Add

Two vectors P1(x1,y1) and P2(x2,y2) can be added in the following manner:

(x1,y1)+(x2,y2)=(x1+x2,y1+y2)

For example:

Reflect

A vector can be rotated about the origin. A particular instance of rotation is reflection about an axis. For example, Pr is the reflection of P about the X-axis:

This corresponds to the transformation:

(x,y)(x,y)

Vector: Specification

From the mathematical vector, we need to transition to the programmatic vector. The bridge between these two states is the specification. In this step, we come up with a written description of the attributes and methods that our Vector class should possess. The source for this information comes from the mathematical vector that we just studied.

The following is the specification of the Vector class:

Attributes

This choice is sufficient as any mathematical vector in 2D space can be completely defined with these two attributes.

Methods

 

Vector: Definition

The stage is now set to define the class:

Most methods are self-explanatory. Some require closer attention. Note that all methods except add do not return any value. These are methods that transform the vector itself. The method add however is interesting. It accepts a vector P as an argument! Within the method, a new Vector object is defined, it is the zero-vector. The current vector is added with P and result is stored in the newly created vector result. This is finally returned.

 

Collection of Vectors

The whole point of having a class is to have objects. The class is just a template. Consider the following use case of a collection of objects:

The list triangle is a collection of objects of type Vector. In this instance, triangle represents the following triangle:

 

We could now ask various questions here, one of which is this: how do we compute the lengths of the sides of this triangle?

In this way, we could also define a square to be a list of four vectors. That brings to a close the discussion on object oriented programming in Python. We will cover these concepts in greater detail when we study Java.