Object Oriented Programming in Python

 

Python is a multi-paradigm programming language. It supports different programming approaches.

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
  • behaviour

 

Let's take an example:

A car is an object, as it has the following properties:

model, year, color as attribute and mileage,speed as behaviour

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

Main concepts of OOPS:

  •     Class
  •         Objects
  •         Inheritance
  •         Encapsulation
  •         Polymorphism

 Class:

A class is a blueprint for the object or a template for an object a class describes the contents of the objects that belong to it: it describes an aggregate of data fields (called instance variables), and defines the operations (called methods).

Class definition syntax:

Class classname:

       #statement

 

Object:

an object is an element (or instance) of a class; objects have the behaviors of their class. The object is the actual component of programs, while the class specifies how instances are created and how they behave.

 

Creating Class and Object in Python:

class car:

 

    # class attribute

    vehicle = "car"

 

    # instance attribute

    def __init__(self, model,year):

        self.model = model

        self.year = year

# instantiate the car class

bmw = car(“x1”,2020)

audi = car("x2",2022)

# access the class attributes

print("bmw is a {}".format(bmw.__class__.vehicle))

print("audi is also a {}".format(audi.__class__.vehicle))

 

# access the instance attributes

print(" bmw {} is  manufactured in {} ".format( bmw.model, bmw.year))

print("audi {} is  manufactured in {} ".format( audi.model,audi.year))

 

Output:

bmw is a car

audi is also a car

bmw x1 is  manufactured in 2020

audi x2 is  manufactured in 2022

 

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

These attributes are defined inside the __init__ method of the class. It is the initializer method that is first run as soon as the object is created.

Then, we create instances of the car class. Here, bmw  and audi are references (value) to our new objects.

We can access the class attribute using __class__.vehicle. Class attributes are the same for all instances of a class. Similarly, we access the instance attributes using bmw.model and bmw.year. However, instance attributes are different for every instance of a class.

 

 

Methods:

Methods are functions defined inside the body of a class. They are used to define the behaviors of an object.

 

Creating Methods in Python:

class car:

 

    # class attribute

    vehicle = "car"

 

    # instance attribute

    def __init__(self, model,year):

        self.model = model

        self.year = year

    # instance method

    def mileage(self, mileage):

        return "{} has mileage of {}".format(self.model, mileage)

 

    def speed(self, speed):

        return "{} has a max speed of{}".format(self.model,speed)

 

# instantiate the object

Car = bmw("x1",2020)

 

# call our instance methods

print(bmw.mileage("20km"))

print(bmw.speed(“200km/s”))

 

Output:

x1 has mileage of 20km

x1 has a max speed of200km per sec

 

In the above program, we define two methods mileage () and speed ().These are called instance methods because they are called on an instance object bmw.

 

Inheritance:

Inheritance is a way of creating a new class for using details of an existing class without modifying it. The newly formed class is a derived class (or child class). Similarly, the existing class is a base class (or parent class).

 

Use of inheritance in python :

class students:

    def __init__(self,name,reg_no):

        self.name=name

        self.reg_no=reg_no

    def tamil(self,mark):

        return "{} has scored {} in tamil".format(self.name,mark)

    def english(self,mark):

        return "{} has scored {} in english".format(self.name,mark)

 

class mathsgroup(students):

    def __init__(self,name,reg_no):

        # call super() function

        super().__init__(name,reg_no)

    def maths(self,mark):

        return "{} has scored {} in maths".format(self.name,mark)

    def physics(self,mark):

        return "{} has scored {} in physics".format(self.name,mark)

   

s1=mathsgroup('sugu',123456)

 

print(s1.tamil(95))

print(s1.english(98))

print(s1.maths(90))

print(s1.physics(89))

 

Output:

sugu has scored 95 in tamil

sugu has scored 98 in english

sugu has scored 90 in maths

sugu has scored 89 in physics

 

In the above program, we created two classes, students (parent class) and mathsgroup (child class). The child class inherits the functions of parent class. We can see this from the tamil()method. we extend the functions of the parent class, by creating a new maths() method.

Additionally, we use the super() function inside the __init__ () method. This allows us to run the __init__ () method of the parent class inside the child class.

 

 

Encapsulation:

Using OOP in Python, we can restrict access to methods and variables. This prevents data from direct modification which is called encapsulation. In Python, we denote private attributes using underscore as the prefix i.e single _or double__.

Data Encapsulation in Python:

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()

c.sell()

 

# change the price

c.__maxprice = 1000

c.sell()

 

# using setter function

c.setMaxPrice(1000)

c.sell()

Output

Selling Price: 900

Selling Price: 900

Selling Price: 1000

In the above program, we defined computer class.

We used __init__() method to store the maximum selling price of computer. Here, notice the code c.__maxprice = 1000

Here, we have tried to modify the value of __maxprice outside of the class. However, since __maxprice is a private variable, this modification is not seen on the output.

As shown, to change the value, we have to use a setter function setmaxprice() which takes price as a parameter.

 

Polymorphism:

Polymorphism is an ability (in OOP) to use a common interface for multiple forms (data types).

 

Using Polymorphism in Python:

class windows7:

 

    def blutooth(self):

        print("windows 7 doesn’t have blutooth compatablity")

 

class windows10:

 

    def blutooth (self):

        print("widows 10 have blutooth capability")

 

# common interface

def blutooth_test(os):

    os.blutooth()

 

#instantiate objects

hp =windows7()

lenovo =windows10()

 

# passing the object

blutooth_test(hp)

blutooth_test(lenovo)

 

Output:

windows 7 doesn’t have blutooth compatablity

widows 10 have blutooth capability

 

In the above program, we defined two classes windows7 and windows10. Each of them have a common blutooth method. However, their functions are different.

To use polymorphism, we created a common interface i.e blutooth_test function that takes any object and calls the object's blutooth method. Thus, when we passed the hp and lenovo objects in the bluttoth_test function, it ran effectively.

 

Comments

Popular posts from this blog

Oracle Database Server Architecture: Overview

Oracle E-Business Suite (EBS) - Introduction

Advantages and Disadvantages of React Native