Wednesday, January 22, 2014

Object-Oriented Programming

Object-Oriented Programming revolves around representing concepts as objects. Objects have attributes to describe them and methods that can be used on them. Classes are used to create instances of a particular kind of object. Common examples of classes are str, int, tuple, float etc. The __init__ method is used to define attributes of an object. For example a class made to represent a point would have attributes x position and y position. Methods allow us to find information or change an object. Using the previous example, we could have methods such as distance from origin, distance between two points, midpoint between two points etc. In the case of the last method 'midpoint', the method returns an instance of the class point. By including the method __str__, you can create a string representation of an object, for example an appropriate representation of a point would be a tuple of the x and y coordinates (x, y). Inheritance is another key feature of Object-Oriented Programming. Inheritance allows a newly formed class to have access to all attributes and methods of a base class. This is very useful when creating a new class that is very similar to an existing with a few modifications. An object of a derived class will have all the attributes of the base class and could call any method from the base class. The function isinstance(obj, cla) checks wether an object obj belongs to class cla or a class that is derived from cla.