Previous Index Next

Object Oriented Programming Concept

There are two common programming methods: procedural programming and object-oriented programming (OOP). So far you have been creating procedural programs.

Procedural Programming

In a procedural program, data is typically stored in a collection of variables and there is a set of functions that perform operations on the data. The data and the functions are separate entities. Usually, the variables are passed to the functions that perform the desired operations. As you might imagine, the focus of procedural programming is on creating the procedures or functions, that operate on the program’s data. Procedural programming works well. However, as programs become larger and more complex, the separation of a program’s data and the code that operates on the data can lead to problems.

Object Oriented programming

The object-oriented programming design models the real world well and overcomes the shortcomings of procedural paradigm. It views a problem in terms of objects and thus emphasizes on both procedures as well as data.

An object is an entity that combines both data and procedures in a single unit. An object’s data items, also referred to as its attributes, are stored in member variables. The procedures that an object performs are called its member functions. This wrapping of an object’s data and procedures together is called encapsulation.

Not only objects encapsulate associated data and procedures, they also permit data hiding. Data hiding refers to an object’s ability to hide its data from code outside the object. Only the object’s member functions can directly access and make changes to the object’s data.

OOP in Python

In Python, everything is an object. This includes things like numbers, strings, lists, sets, tuples, and dictionaries. An object has two aspects:

  • Instance variables containing data; these describe the state of the object
  • Methods that provide means of manipulating the object.

In other words, an object combines data and methods together. Look at the following code segment:

>>> s = [14, 5, 9, 6]
>>> s.append(15)

In above code, the list [14, 5, 9, 6] is an object. In order to use an object, there must be a way to reference them. In Python this is done by binding objects to names. Here, list object is bounded by name s. The append() is a method that you can use with lists, s.append(15) changes the named list to have the value [14, 5, 9, 6,15].

Every object belongs to some class. An object "knows" what class it belongs to, and can use class data and class methods. To check what is the class of an object call the type() function like this:

>>> type(s)
<class 'list'>

In next section, we will learn about how to create your own class.

Previous Index Next