Books-aj.svg aj ashton 01f.png


Object Oriented Programming

OOP is a programming approach where objects are defined with methods (functions, actions or events) and properties (values, characteristics), resulting in more readable, more reusable code.

Lets say you're writing a program where you need to keep track of multiple cars. Each car has different characteristics like mileage, color, and top speed, but lucky for us they all can perform some common actions like braking, accelerating, and turning.

Instead of writing code separately for each car we could create a class called 'Car' that will be the blueprint for each particular car.

Constructing a class

Class is the name given to a generic description of an object. In python you define a class method (an action, event, or function) using the following structure:

class <<name>>:
    def <<method>> (self [, <<optional arguments>>]):
        <<Function codes>>

Let's take a detailed look. We define our object using the 'class' keyword, the name we want, and a colon. We define its methods as we would a normal function: only one indent with 'self' as its first argument (we get to this later). So our example car class may look like this:

class Car:
    def brake(self):
        print "Brakes"

    def accelerate(self):
        print "Accelerating"
Attention yellow.svg The first letter of the class name should be capitalized (Car - not car). This a very common convention, although not required by the language.
Attention yellow.svg This is an example of encapsulation, where processing instructions are defined as part of another structure for future reuse.

But how do I use it?

Once you have created the class, you actually need to create an object for each instance of that class. In python we create a new variable to create an instance of a class. Example:

car1 = Car # car 1 is my instance for the first car
car2 = Car

# And use the object methods like

Using the parentheses ("calling" the class) tells Python that you want to create an instance and not just copy the class definition. You would need to create a variable for each car. However, now each car object can take advantage of the class methods and attributes, so you don't need to write a brake and accelerate function for each car independently.


Right now all the cars look the same, but let's give them some properties to differentiate them.

A property is just a variable that is specific to a given object. To assign a property we write it like:
car1.color = "Red"
And retrieve its value like:
print car1.color

It is good programming practice to write functions to get (or retrieve) and set (or assign) properties that are not 'read-only'. For example:

class car:
    ... previous methods ...
    def set_owner(self,Owners_Name): # This will set the owner property
        self._owner = Owners_Name

    def get_owner(self): # This will retrieve the owner property
        return self._owner

Notice the single underscore before the property name; this is a way of hiding variable names from users.

Beginning from Python 2.2, you may also define the above example in a way that looks like a normal variable:

class car:
    ... previous methods ...
    owner = property(get_owner, set_owner)

Then, when you do like mycar.owner = "John Smith", the set_owner function is instead called transparently.

Attention yellow.svg Think of a property that needs to be validated before it can be assigned. If we don't hide such a variable from the user, it can create a security risk in our program.

Extending a class

Let's say we want to add more functions to our class, but we are reluctant to change its code for fear that this might mess up programs that depend on its current version. The solution is to 'extend' our class. When you extend a class you inherit all the parent methods and properties and can add new ones. For example, we can add a start_car method to our car class. To extend a class we supply the name of the parent class in parentheses after the new class name, for example:

class new_car(car):
   def start_car(self):
      self.on = True

This new class extends the parent class.

Attention yellow.svg When methods and attributes are passed down to new classes in hierarchies, it is called Inheritance.

Special Class Methods

In Python the names of special methods begin and end with double underscore - __. For example, the special method __init__ is used to initialize the state of newly created objects.For instance, we could create a new car object and set its brand, model, and year attributes on a single line, rather than expending an additional line for each attribute:

class new_car(car):
    def __init__(self,brand, model, year):
        # Sets all the properties
        self.brand = brand
        self.model = model
        self.year = year

    def start_car(self):
        """ Start the cars engine """
        print "vroem vroem"

if __name__ == "__main__":
    # Creates two instances of new_car, each with unique properties
    car1 = new_car("Ford","F-150",2001)
    car2 = new_car("Toyota","Corolla",2007)


For more information on classes go to the Class Section in Study Guides.


Crystal Clear app kedit.svg
Face-blush.svg Completion status: About halfway there. You may help to clarify and expand it.

  This article uses material from the Wikipedia page available here. It is released under the Creative Commons Attribution-Share-Alike License 3.0.


Manage research, learning and skills at IT1me. Create an account using LinkedIn to manage and organize your IT knowledge. IT1me works like a shopping cart for information -- helping you to save, discuss and share.

  Contact Us  |  About |  IT Training & References |  IT Careers |  IT Hardware |  IT Software |  IT Books