Object-Oriented Programming

Defining Classes#

Example: Defining a Fraction class.

class Fraction:
def __init__(self, top, bottom):
self.num = top
self.den = bottom

self is a special parameter which makes reference to the object itself and is always the first parameter. However, it is not supplied as an argument.

Static Variables#

Static variables are shared among all instances of the class. For example, if we have anEmployee class, num_of_employees can be a static variable which keeps count of the total number of employees.

class Employee:
num_of_employees = 0

Printing an Object#

To print an object, we can define a method 'show'.

def show(self):
print(self.num, '/', self.den)

Otherwise, we need to tell Python how to convert the object into a string by overriding the __str__ method.

def __str__(self):
return str(self.num) + '/' + str(self.den)

Overriding Default Methods#

Just as how we overrode the default __str__ method, we can override the other default methods such as the + arithmetic operator.

def __add__(self,otherfraction):
newnum = self.num*otherfraction.den + self.den*otherfraction.num
newden = self.den * otherfraction.den
return Fraction(newnum,newden)

Deep Equality#

Shallow equality compares the references of two objects. To have deep equality, where we compare the contents of the two objects, we need to override the __eq__ method. Other relational operators such as less than can be achieved by overriding the __le__ method.

def __eq__(self, other):
firstnum = self.num * other.den
secondnum = other.num * self.den
return firstnum == secondnum