Python Object & Class

Python Object Oriented Programming

Programming languages are frequently distinguished by their programming paradigm. A programming paradigm is one way of viewing and interacting with data. Object-Oriented and Functional are the two fundamental paradigms. Object-Oriented Programming is based on data structures called objects, which hold both data (properties or attributes) and code (procedures or methods). Python Object-oriented programming (OOP) is a method of organizing a program by grouping together related characteristics and behaviors into separate objects. With the help of examples, we will learn about Python Object-Oriented Programming (OOP) and its core concepts in the article below.

Object-Oriented Programming

Alan Kay developed the phrase “Object-Oriented Programming” (OOP) in 1966, while still in graduate school. The goal of Object-Oriented Programming (OOP) is to create “objects.” An object is a collection of interconnected variables and functions. These variables are frequently referred to as object attributes, and functions are referred to as object behavior. These objects improve and clarify the program’s structure.

An automobile, for example, can be an item. If we regard the car to be an item, its properties include its color, model, price, brand, and so on. And its behavior/function would be acceleration, deceleration, and gear shift.

Creating objects is a popular method for solving computer problems. Python Object-oriented Programming (OOPs) is a programming paradigm that makes use of objects and classes. A class can be viewed as a “blueprint” for things. The primary idea behind OOPs is to tie the data and the functions that act on it as a single unit so that no other portion of the code may access it.

Object-oriented languages are governed by a number of principles. The following are the major principles of a Python object-oriented programming system:

  • Class
  • Objects
  • Methods
  • Inheritance
  • Encapsulation
  • Polymorphism
  • Data Abstraction

Class

Classes are used to generate data structures that are unique to the user. Classes define methods, which identify the behaviors and activities that a class-created object can execute with its data. A class is a blueprint for an object and can be thought of as a collection of objects. For example, if you have an employee class, it should have an attribute and method, such as an email id, name, age, salary, and so on.

  • Defining a class –

All class definitions begin with the class keyword, followed by the class name and a colon. Any code indented beneath the class definition is assumed to be part of the class’s body. Let’s look at an example to help you understand.

                    

class Employee:
       def __init__(self):
pass

The class keyword is used here to define an empty class Employee. We create instances from classes. An __init__ method must be defined within the class using def. This is the initializer that will be used subsequently to instantiate objects. It is analogous to a constructor in Java.

Object

The object is a self-contained entity with state and behavior. It might be any real-world object, such as a mouse, keyboard, chair, table, pen, and so on. In Python, everything is an object, and nearly everything has attributes and functions.

The process of creating a new object from a class is known as instantiating an object. When a class is defined, only the object’s description is specified. As a result, no memory or storage space is allocated. We build the class’s object to allocate memory. The objector instance is made up of real facts or information. Let’s make an object of the above-mentioned class –

Here, obj is an object of the class Employee.

Assume we have Employee information. Now we’ll look at how to create the Employees class and objects.

Example 1: Creating Class and Object in Python

                    

class Employee:
    # instance attribute
    def __init__(self, name, salary, designation):
        self.name = name
        self.salary = salary
        self.designation = designation

# instantiate the Employee class
e1 = Employee('David', 20000, 'CMO')
e2 = Employee('Henry', 45000, 'VP')

# access the instance attributes
print(e1.name, 'has a salary of', e1.salary, 'and his position is', e1.designation)
print(e2.name, 'has a salary of', e2.salary, 'and his position is', e2.designation)

Output

                    

David has a salary of 20000 and his position is CMO
Henry has a salary of 45000 and his position is VP

In the prior program, we defined a class called Employee. After that, we define characteristics. An object’s properties are its distinguishing features. These attributes are defined via the class’s __init__ method. As soon as the object is formed, the initializer method is called.

After that, we make instances of the Employee class. In this case, e1 and e2 are the values of our new objects.

Similarly, we use e1.name, e1.salary, and e1.designation to retrieve the instance characteristics. Instance attributes, on the other hand, differ for each instance of a class.

Methods

In programming, Methods are functions that are specified within a class and can only be called from a class instance. Methods are the functions that we employ to describe how objects behave.

Example 2: Creating Methods in Python

                    

class Employee:
    # instance attribute
    def __init__(self, name, salary, designation):
        self.name = name   

    # instance method
    def pos(self, pos):
        return '{} is {} of the company'.format(self.name, pos)

    def sal(self, sal):
        return "{} has a salary of {}".format(self.name, sal)

# instantiate the Employee class
e1 = Employee('David', 45000, 'CMO')

# call our instance methods
print(e1.pos('CMO'))
print(e1.sal(45000))

Output

                    

David is CMO of the company
David has a salary of 45000

In the above program, we define two methods, pos() and sal(). These are referred to as instance methods since they are invoked on an instance object, such as e1.

Inheritance

Inheritance is the process through which one class inherits the attributes and methods of another without changing them. The class from which the attributes and methods are inherited is referred to as the Parent class. The Child class is the one that inherits the parent class’s properties. These classes can inherit information and functionality from that class while also expanding on it. It allows us to reuse code that we’ve already written in other classes.

The following are the advantages of inheritance:

  • It accurately depicts real-world relationships.
  • It ensures a code’s reusability. We don’t have to rewrite the same code again and over. It also allows us to add new features to a class without having to alter them.
  • It is transitive, which implies that if class B inherits from another class A, then all of B’s subclasses will also inherit from class A.

Example 3: Use of Inheritance in Python

                    

class Car:     #Parent class
    def __init__(self, name, color):
         self.name = name
         self.color = color
    def description(self):               
         return f'The {self.name} car is available in {self.color} colour.'

class BMW(Car):    #Child class
    pass

class Audi(Car):   #Child class
    def audi_desc(self):
         return 'Audi is one of the best car brands in the world.'

obj1 = BMW('BMW 5-series', 'White')
print(obj1.description())

obj2 = Audi('Audi R8 e-tron','Black')
print(obj2.description())
print(obj2.audi_desc())

Output

                    

The BMW 5-series car is available in White colour.
The Audi R8 e-tron car is available in Black colour.
Audi is one of the best car brands in the world.

We’ve built two child classes, “BMW” and “Audi,” which have inherited the parent class’s methods and properties. In the BMW class, we have included no extra features or approaches. In addition, there is one more method within the class Audi.

Take note to how the parent class’s instance function description() is accessible to child class objects via obj1.description() and obj2.description(). Additionally, the Audi class’s distinct method is accessible via obj2.audi_desc().

Encapsulation

We can restrict access to methods and variables in Python using OOP. This is known as encapsulation because it protects data from direct change. Encapsulation is the concept of binding data to functions that act as a security function to protect that data. This restricts direct access to variables and methods and can prevent data from being accidentally modified.

In Python, we use underscore as the prefix to designate private characteristics, i.e. single or double. You can protect methods and attributes by placing a single underscore (_) or double underscore (__) before their names.

Example 4: Data Encapsulation in Python

                    

class Bike:
    def __init__(self):
        self.__maxprice = 100000

    def buy(self):
        print('Buying Price:', self.__maxprice)

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

b = Bike()
b.buy()

# change the price
b.__maxprice = 70000
b.buy()

# using setter function
b.setMaxPrice(99000)
b.buy()

Output

                    

Buying Price: 100000
Buying Price: 100000
Buying Price: 99000

We defined a Bike class in the previous program. To save the maximum purchase price of Computer, we used the __init__() method. We attempted to change the price. However, we are unable to update it since Python considers the __maxprice to be private properties.

To alter the value, we must use a setter method, such as setMaxPrice(), which accepts price as an argument.

Polymorphism

When the phrase Polymorphism is broken down, we obtain “poly” – many and “morph” – forms. It refers to the ability to manage objects differently based on what they are in the context of OOP languages. It enables us to define several methods for dealing with objects based on their derived class. Assume we need to color a form and there are several shape alternatives (rectangle, square, circle, triangle). We could, however, use the same procedure to color any form. This is known as polymorphism. It refers to functions with the same names but differing functionalities in OOP.

Example 5: Using Polymorphism in Python

                    

class Tiger:
    def legs(self):
        print('Tiger has 4 legs')

    def nature(self):
        print('Tiger is dangerous')

class Peacock:
    def legs(self):
        print('Peacock has 2 legs')

    def nature(self):
        print('Peacock is calm')

# common interface
def legs_test(species):
    species.legs()

#instantiate objects
a = Tiger()
b = Peacock()

# passing the object
legs_test(a)
legs_test(b)

Output

                    

Tiger has 4 legs
Peacock has 2 legs

We defined two classes in this Polymorphism program: Tiger and Peacock. They all share the legs() and nature() methods. Their duties, however, are distinct. To use polymorphism, we established a common interface, legs_test(), which accepts any object and calls its legs() method. As a result, when we gave the “a” and “b” objects to the legs_test() function, it worked properly.

Data Abstraction

Data abstraction and encapsulation are frequently used interchangeably. Because data abstraction is accomplished by encapsulation, the terms are practically synonymous. Abstraction is used to hide internal information or implementations of a function and just reveal its functions. To begin creating an abstraction class, import the ABC class from the abc module. This allows you to construct abstract methods within it. ABC is an abbreviation for Abstract Base Class.

Frequently Asked Questions

Q1. What is Python object-oriented programming?

Object-Oriented Programming is based on data structures called objects, which hold both data (properties or attributes) and code (procedures or methods). Python Object-oriented programming (OOP) is a method of organizing a program by grouping together related characteristics and behaviors into separate objects.

The goal of Python Object-Oriented Programming (OOP) is to create “objects.” An object is a collection of interconnected variables and functions. These variables are frequently referred to as object attributes, and functions are referred to as object behavior. These objects improve and clarify the program’s structure.

Q2. Is Python 100% object-oriented?

The Python programming language supports all of the concepts of “object-oriented programming,” but it is not entirely object-oriented because code in Python can be produced without the usage of classes. Python allows you to write both object-oriented and procedural programs. Python is a general-purpose programming language; you can write whatever you want in Python as long as you utilize proper grammar.

Share with friends

Customize your course in 30 seconds

Which class are you in?
5th
6th
7th
8th
9th
10th
11th
12th
Get ready for all-new Live Classes!
Now learn Live with India's best teachers. Join courses with the best schedule and enjoy fun and interactive classes.
tutor
tutor
Ashhar Firdausi
IIT Roorkee
Biology
tutor
tutor
Dr. Nazma Shaik
VTU
Chemistry
tutor
tutor
Gaurav Tiwari
APJAKTU
Physics
Get Started

Leave a Reply

Your email address will not be published. Required fields are marked *

Download the App

Watch lectures, practise questions and take tests on the go.

Customize your course in 30 seconds

No thanks.