Codementor Events

An Overview of Object-Oriented Programming Using Python

Published Mar 23, 2017Last updated Mar 24, 2017
An Overview of Object-Oriented Programming Using Python

A Basic Intro

We have been writing code around functions with certain input, algos to manipulate them, in hopes to return something. Whether it‘s a search algorithm, a function to test something, or scripts that manipulate some external resources based on the given input, we've been doing this for a while. We call this style of writing code a "procedural way of programming." This is good practice, but it's not ideal for larger projects. For larger projects, we use another style of programming called "object oriented way of programming."

object-oriented programming

In this method, we break a task down into objects, which uses some defined methods and data. It is a model organized around "class/object" rather than functions. Objects are modeled after real-world objects.

So object-oriented programming is a programming paradigm that is organized around objects (involving both data and methods) and it aims to take advantage of code re-usability.

What is Class?

Class is a logical grouping of data and functions (referred as "methods" when defined within a class). Classes are created after real-word objects: concepts like customer, product, or urllib. So, rather than just putting random things together under the name "class", we try to create classes where there are logical connections between things.

Classes can be thought of as blueprints of creating objects. When we make a blueprint of a building, we're not actually making a building; we are defining its various properties, like number of rooms, basic layout, and functionality. When our blueprint is ready, we can make any number of buildings based on that blueprint, add additional functions, and change defined functions.

Defining a sample class in Python

 class Class_name(object):
    """ docstring for class_name """
    pass

Now let's look at an example. Suppose we have to write some code, which stores basic information about the student of a certain school.

 class Student(object):
    """ A base class of student for school xyz """ 

	total_student =0

	def __init__(self,name,standard,average_grade):
    	self.name = name
    	self.standard= standard
    	self.average_grade= average_grade
    	Student.total_student += 1
    
	def display_number_of_student(self):
    	print "Total Number of Student: %d" %Student.total_student
    
	def display_info(self):
    	print "Name:", self.name, ", Standard: ", self.standard, 
		", Average Grade:", self.average_grade

Creating an Object From Class

To create an object [Instance] from class, we will call the class in the same way we would a function — with the arguments (minus self) given to __init__ function.

 smith= Student("Jon Smith",8,'B')
 kumar= Student("Rahul Kumar",9,'C')

Oh, things got too hasty? Don’t worry. We will go through everything step by step.

__init__

This would be the first method in a class and it is called "initialize" or "constructor". The first argument to __init__ would be self (we will talk about this next). Along with self, it takes additional argument, which we are going to use and manipulate in the class. These arguments are called attributes.

A good practice is to define all the attributes inside the __init__.

self

So what is self? Along with __init__, every method in student class takes self as their argument.

To create our first instance(object) smith, we have called the class along with some arguments, which go to _ init _ function. When we say smith is the instance, self refers to smith. So When we create an instance, instead of using smith= Student("smith", "Jon smith", 8,'B'), we will use smith= Student("Jon smith", 8,'B').
Python automatically interrupts self as smith. We don't have to explain this too much.

Now, why is self present in other methods?

When we access any method of class "student" using smith, every method will interrupt self as smith and process the information regarding that instance. Methods are called using instance_name.method_name(argus) so here, we haven't defined self. Here, instance_name is taken as self. Another way to define this would be instance_name.method_name(instance_name,argus).

For example: When we call smith.display_info(), the output would be:

Name: Jon Smith , Standard: 8 , Average Grade: B,

but when we call kumar.display_info(), the output would be:

Name: Rahul Kumar , Standard: 9 , Average Grade: C

When we create an Instance, __init__ is called and a fully initialized object is ready. Now, with this object we can access all the methods defined inside the class.

A lot of New Words!

Throughout the post, you might have encountered a few new words that don't make sense if you're new to object-oriented programming. Now is a perfect time to define them. Let's start:

1. Class:

A logical grouping of data and functions, a blueprint, and a building block of Python.

Example of class: In our example, Student is a class, which is a blueprint of the students of a certain school.

2. Instance:

When we call on the class, we create an instance of that class. We can create as many instance as we want for a particular class.

Example: smith and kumar are two instancess of the class Student.

3. Methods/Instance Methods:

Functions defined inside the class are called Methods. Sometimes theses are also referred to as "Instance Methods", as these methods take self as their first argument (require an instance to operate).

Example: function display_number_of_student() and display_info() are called methods.

4. Attributes:

The different variables defined inside the __init__ function are called attributes.

Example: Name, Standard, and average_grade are attributes of class Student.

5. Instance Variable:

Variables that are defined inside an instance method and only belong to that particular instance method are called "instance variable."

6. Class Variable:

Class variable is a variable that is shared by all instances of a class. Class variable can be accessed from inside or outside of the class. Class variables are defined within a class but outside any of the class's methods.

Example: variable total_student in class Student is a class variable.

Accessing Class Variable

We know that class variable is accessable from inside or outside the class.

 Student.total_student

Output:

 2

Again,

 print smith.total_student
 print kumar.total_student

Output:

 2
 2

If we try to access an attribute that is not defined, Python will raise an "AttributeError".

Putting It all together

We want to create a student log for a certain school. To do so, we first have to prepare a blueprint (i.e created a class called Student). Till now, we haven't created logs for any student. We just outlined information and function.

Now, we can create our first instance by giving proper argument to Student class [ smith= Student("Jon Smith",8,'B')]. Here. we are telling Python to use the student blueprint to make a student log, which we will refer to as smith.

Again, when we call kumar= Student("Rahul Kuamr",9,"C"), we're telling Python to use the student blueprint to create a student log, which we will refer to as kumar.

smith and kumar are both known as instances of the class Student. We can create as many instances as we want. These instances have access to instance methods and class variables.

Final Note:

Thus far, we have talked about the basics of class, why they are useful, and how to use them (hopefully). Object oriented programming is a big topic. This post was not designed as a one-stop for classes. Read more about classes and Python here to get a deeper insight.

If you have any questions, feel free to visit my website and let me know!

Discover and read more posts from sajjan Kumar
get started
post commentsBe the first to share your opinion
Show more replies