Day 12 & 13. Object-Oriented Programming in Python.

Hello Everyone…

As you know we are going on an advanced topic day by day in python. So today we are discussing object-oriented programming in python, it’s quite simple as in other programming languages.

Let’s Start.

Introduction to OOPs in Python

One of the popular approaches to solve a programming problem is by creating objects. This is known as Object-Oriented Programming (OOP).

An object has two characteristics:

  • attributes
  • behavior

Let’s take an example:

A parrot is an object,

  • name, age, color are attributes
  • singing, dancing is behavior

The concept of OOP in Python focuses on creating reusable code. This concept is also known as DRY (Don’t Repeat Yourself).

In Python, the concept of OOP follows some basic principles:

inheritance process of using details from a new class without modifying the existing class.EncapsulationHiding the private details of a class from other objects. polymorphism concept of using common operation in different ways for different data input.

Class

We can think of a class as a sketch of a parrot with labels. It contains all the details about the name, colors, size, etc. Based on these descriptions, we can study about the parrot. Here, a parrot is an object.

The example of a class of parrot can be :

class Parrot:
pass

Here, we use class keyword to define an empty class Parrot. From class, we construct instances. An instance is a specific object created from a particular class.

Object

The example for the object of parrot class can be:

obj = Parrot()

Here, obj is the object of class Parrot.

Suppose we have details of the parrot. Now, we are going to show how to build the class and objects of parrot.

Example 1: Creating Class and Object in Python

class Parrot:# class attributespecies = “bird”# instance attributedef __init__(self, name, age):self.name = nameself.age = age# instantiate the Parrot classblu = Parrot(“Blu”, 10)woo = Parrot(“Woo”, 15)# access the class attributesprint(“Blu is a {}”.format(blu.__class__.species))print(“Woo is also a {}”.format(woo.__class__.species))# access the instance attributesprint(“{} is {} years old”.format( blu.name, blu.age))print(“{} is {} years old”.format( woo.name, woo.age))

When we run the program, the output will be:

Blu is a bird
Woo is also a bird
Blu is 10 years old
Woo is 15 years old

In the above program, we create a class with the name Parrot. Then, we define attributes. The attributes are a characteristic of an object.

Then, we create instances of the Parrot class. Here, Blu and woo are references (value) to our new objects.

Then, we access the class attribute using __class __.species. Class attributes are the same for all instances of a class. Similarly, we access the instance attributes using blu.name and blu.age. However, instance attributes are different for every instance of a class.

To learn more about classes and objects, go to Python Classes and Objects

Methods

Example 2: Creating Methods in Python

class Parrot:# instance attributesdef __init__(self, name, age):self.name = nameself.age = age# instance methoddef sing(self, song):return “{} sings {}”.format(self.name, song)def dance(self):return “{} is now dancing”.format(self.name)# instantiate the objectblu = Parrot(“Blu”, 10)# call our instance methodsprint(blu.sing(“‘Happy’”))print(blu.dance())

When we run the program, the output will be:

Blu sings 'Happy'
Blu is now dancing

In the above program, we define two methods i.e sing() and dance(). These are called instance method because they are called on an instance object i.e blu.

Inheritance

Example 3: Use of Inheritance in Python

# parent classclass Bird:def __init__(self):print(“Bird is ready”)def whoisThis(self):print(“Bird”)def swim(self):print(“Swim faster”)# child classclass Penguin(Bird):def __init__(self):# call super() functionsuper().__init__()print(“Penguin is ready”)def whoisThis(self):print(“Penguin”)def run(self):print(“Run faster”)peggy = Penguin()peggy.whoisThis()peggy.swim()peggy.run()

When we run this program, the output will be:

Bird is ready
Penguin is ready
Penguin
Swim faster
Run faster

In the above program, we created two classes i.e. Bird (parent class) and Penguin (child class). The child class inherits the functions of the parent class. We can see this from the method. Again, the child class modified the behavior of the parent class. We can see this from who is this() method. Furthermore, we extend the functions of the parent class, by creating a new method.

Additionally, we use super() a function before __init__() method. This is because we want to pull the content of method from the parent class into the child class.

Encapsulation

Example 4: Data Encapsulation in Python

class Computer:def __init__(self):self.__maxprice = 900def sell(self):print(“Selling Price: {}”.format(self.__maxprice))def setMaxPrice(self, price):self.__maxprice = pricec = Computer()c.sell()# change the pricec.__maxprice = 1000c.sell()# using setter functionc.setMaxPrice(1000)c.sell()

When we run this program, the output will be:

Selling Price: 900
Selling Price: 900
Selling Price: 1000

In the above program, we defined a class Computer. We use the method to store the maximum selling price of the computer. We tried to modify the price. However, we can’t change it because Python treats the __maxprice as private attributes. To change the value, we used a setter function i.e which takes price as a parameter.

Polymorphism

Suppose, we need to color shape, there is multiple shape option (rectangle, square, circle). However, we could use the same method to color any shape. This concept is called Polymorphism.

Example 5: Using Polymorphism in Python

class Parrot:def fly(self):print(“Parrot can fly”)def swim(self):print(“Parrot can’t swim”)class Penguin:def fly(self):print(“Penguin can’t fly”)def swim(self):print(“Penguin can swim”)# common interfacedef flying_test(bird):bird.fly()#instantiate objectsblu = Parrot()peggy = Penguin()# passing the objectflying_test(blu)flying_test(peggy)

When we run the above program, the output will be:

Parrot can fly
Penguin can't fly

In the above program, we defined two classes Parrot and Penguin. Each of them has a common method fly() . However, their functions are different. To allow polymorphism, we created a common interface i.e function that can take any object. Then, we passed the objects Blu and Peggy in the function, it ran effectively.

Thank You.

Data Scientist, Blockchain enthusiast, Entrepreneur.