DEV Community


Posted on

Object oriented programming using python

Image description
Python is a great programming language that supports Object Oriented Programming.

What is Object oriented programming?

This is a flexible, powerful paradigm where classes represent and define concepts while objects are instances of classes.

Why use Object Oriented Programming?

  • It makes code more reusable so you don't have to repeat once

  • Makes it easier to work with larger programs.

  • Makes program easy to understand.

A class is a user-defined blueprint from which objects are created.
Classes have attributes and methods associated with them and you can have instances of a class when you create new, individual objects in a certain class.
Image description
For example in the above diagram, we have a class that we have named Fruit.

Banana, apple, pineapple and strawberry are instances of the class Fruit.
An instance is an object that is built from a class and contains real data.

Attributes are the characteristics associated to a class or a certain instance of a class. Like in our example apple can have attributes: color(red) and texture(smooth)

Methods are functions that operate on the attributes of a specific instance of a class. In our apple example ,we can have a cut method which turns it to pieces or eat method which reduces the apple size with every bite.

Creating and defining classes in Python

We create and define classes in Python similar to how we define functions.
Start with the class keyword, followed by the name of the class and a colon. Class names start with a capital letter. After the class definition line is the class body, indented to the right.

class Fruit:
  color=" "
  texture=" "
Enter fullscreen mode Exit fullscreen mode

We can set the attributes of our class instance by accessing them using dot notation.
Dot notation can be used to set or retrieve object attributes as well as call methods associated with them.

Enter fullscreen mode Exit fullscreen mode

We created a Fruit instance called apple and set the color and texture attributes. Another instance of Fruit can be created and set different attributes.

Enter fullscreen mode Exit fullscreen mode

Special methods

The examples above are classes and objects in their simplest form and are not really useful in real life applications.

Special methods start and end with two underscore characters.
There are many special methods that you can use to customize classes in Python.

All classes have a special method __ init __() ,which is always executed when the class is being used to create a new object. It is used to assign values to object properties or other operations that are necessary to do when the object is being created.

class Fruit:
  def __init__(self,name,color,texture):


Enter fullscreen mode Exit fullscreen mode


Enter fullscreen mode Exit fullscreen mode

The self parameter is a reference to the current instance of
the class, and is used to access variables that belong to the

There is also a __ str __() special method which returns the output in a string format.

class Fruit:
  def __init__(self,name,color,texture):

  def __str__(self):
    return f"{} is a fruit and its {self.color} in color and its {self.texture}"

Enter fullscreen mode Exit fullscreen mode


Apple is a fruit and its red in color and its smooth
Enter fullscreen mode Exit fullscreen mode

An example of method in our Fruit class is as shown below:

class Fruit:
  def __init__(self,name,color,texture):

  def fruity(self):
    return f"{} is {self.color} in color and {self.texture} "

  def describe(self,taste):
    return f"{} is {taste}"


Enter fullscreen mode Exit fullscreen mode


apple is red in color and smooth 
apple is sweet
Enter fullscreen mode Exit fullscreen mode

Fruity and describe are methods in our Fruit class.

There are several key concepts in Object Oriented Programming.
Image description


In object-oriented programming, the concept of inheritance allows you to build relationships between objects, group together similar concepts and reduce code duplication.

A parent class is the class being inherited from.Any class can be a parent class, so the syntax is the same as creating any other class.

A child class is the class that inherits from another class.A child class inherits the properties and methods from its parent but you can also add other properties.
When creating a child class, the name of the parent class is set as the parameter so that it can inherit its functionality.

To keep the inheritance of the parent's init() function,
add a call to the parent's init() function

class Person:
  def __init__(self,name,age): = name
    self.age = age

  def display(self):
    print(" is "+str(self.age)+" years old")

#child class
class Student(Person):
  def __init__(self,name,age,admission,form):
    self.form = form

    # invoking the __init__ of the parent class 

#Creating an object
Aziz = Student("Abdul Aziz","22","6325",4)


>>> Abdul Aziz is 22 years old
Enter fullscreen mode Exit fullscreen mode

From the above example, we have created a child class Student from the parent class Person and it inherits the attributes name and age and method display from its parent.Although, we have added other attributes admission and form to our child class.

Python also has a super() function that will make the child class inherit all the methods and properties from its parent


This concept allows us to restrict access to methods and variables. This prevents data from direct modification. In Python, we denote private attributes using underscore which can either be single _ or double __.

class Computer:

    def __init__(self):
        self.__maxprice = 900

    def sell(self):
        print("Selling Price: {}".format(self.__maxprice))

    def setMaxPrice(self, price):
        self.__maxprice = price

c = Computer()

# change the price
c.__maxprice = 1000

# using setter function
Enter fullscreen mode Exit fullscreen mode


Selling Price: 900
Selling Price: 900
Selling Price: 1000
Enter fullscreen mode Exit fullscreen mode

In the above program ,we have defined a computer class whereby the_init_() method is for storing the maximum selling price of computer.
We try to set max price outside and it cannot be reflected since its a private variable __maxprice hence using a setter function to change the price.


The word polymorphism means having many forms. In programming, polymorphism means the same function name (but performing different activities) which allows flexibility.

class India():
    def capital(self):
        print("New Delhi is the capital of India.")

    def language(self):
        print("Hindi is the most widely spoken language of India.")

    def type(self):
        print("India is a developing country.")

class USA():
    def capital(self):
        print("Washington, D.C. is the capital of USA.")

    def language(self):
        print("English is the primary language of USA.")

    def type(self):
        print("USA is a developed country.")

obj_ind = India()
obj_usa = USA()
for country in (obj_ind, obj_usa):
Enter fullscreen mode Exit fullscreen mode


New Delhi is the capital of India.
Hindi is the most widely spoken language of India.
India is a developing country.
Washington, D.C. is the capital of USA.
English is the primary language of USA.
USA is a developed country.
Enter fullscreen mode Exit fullscreen mode

We have created two classes India and USA .They have similar structure and methods capital,language,type although they are not linked in any way, we are able to use a for loop to iterate them through a common country variable.
This is made possible by polymorphism.

For more understanding of polymorphism concept here are some links:

Top comments (2)

user_bc3898ea30 profile image

Thanks for the code snippets, builds on the explanations ^MJ

hannahmwende profile image

Glad it was of help @user_bc3898ea30