top

Search

Python Tutorial

.

UpGrad

Python Tutorial

Python Object-Oriented Programming

Introduction

Python Object-oriented programming represents a programming paradigm, a collection of concepts establishing a framework for prescribed practices.

At its core, OOP revolves around system modeling through the utilization of objects. Within this context, an object serves as a constituent within a focal system, typically characterized by a particular function and conduct.

Essential to each object are functions known as methods and associated data. Methods, in essence, function as processes for executing operations on data, often necessitating specific parameters as input arguments.

Overview

Python OOP offers a structured approach to software design. It revolves around objects representing real-world entities, each encapsulating data and behavior. Some of the key concepts are class, object, method, inheritance, encapsulation and polymorphism.

OOPs Concepts in Python

Class

A class in Python is a blueprint for constructing objects. It defines a set of attributes and methods that objects derived from the class will have.

The importance of classes lies in their ability to structure and organize code. They allow you to create reusable and maintainable code and model real-world entities in a program. 

Classes include data and behavior, which helps in achieving modularity and abstraction. The role of a class is to define the attributes (data) and methods (functions) that objects of that class will have. It acts as a template or a design for creating objects.

Object

An object can be considered a real-world thing or concept in your program. It's like a copy of a blueprint created from a class. These objects are beneficial because they bring structure and order to your code. They let you deal with data and actions related to those things organizationally.

Imagine objects as individual entities. Each has unique characteristics (like its name, age, color, etc.), which we call attributes.

An object in Python can also perform specific tasks or actions, which we call methods. These actions are defined by the class they belong to.

Method

In Python, methods are like specialized functions within a class that enable objects to perform specific tasks. They serve as the tools that define what an object can do and how it manages its data.

Methods play a crucial role in code organization by neatly covering a class's behaviors. For example, in a "Car" class, methods such as "start_engine" or "turn_off_lights" define the actions a car can take.

What makes methods important is their efficiency and reusability. You can use the same methods with various objects, such as starting the engines of different cars, which simplifies your code.

Additionally, methods ensure that an object's state remains consistent and functions as intended.

Inheritance

Inheritance holds a position of fundamental significance in the context of OOP. It includes the ability of a class to acquire attributes and methods from another class.

This process involves two primary participants: the subclass, also known as the child class, which gains access to the inherited elements, and the superclass, identified as the parent class, serving as the source of these shared methods and attributes.

Polymorphism

Polymorphism in Python is a core concept that enhances code flexibility and extensibility. 

It enables you to interact with objects from different classes as if they all belong to a shared base class. This simplifies coding by eliminating the need to worry about the specific identities of individual objects, making your code more versatile and adaptable.

Think of polymorphism as a way for objects to wear disguises. They might look different on the outside (different classes), but they can all respond to the same basic commands (methods). It makes your code more versatile and adaptable.

Polymorphism has two main roles:

Method Overriding: It lets subclasses provide their unique implementation of a method inherited from a base class.

Method Overloading: It allows you to use the same method name in related classes but customize how each class handles it.

Data Abstraction

Data abstraction is a crucial programming concept that conceals complex details within a class while providing a user-friendly interface. It is crucial for effective software management.

Data abstraction lets us define vital attributes and methods without overwhelming users with technical complexities. It's like offering a simple dashboard for a complex machine, sparing users from understanding the inner workings.

The main goal of data abstraction is to create a clear separation between what users interact with (the interface) and the behind-the-scenes workings. This clarity enhances code maintainability, reduces errors, and promotes smoother collaboration among programmers.

Encapsulation

Encapsulation in Python bundles data and methods into a class, playing a vital role in software design.

Primarily, it safeguards data by limiting direct access and controlling it through designated methods, akin to placing a protective barrier around your data.

Secondly, it organizes code by grouping related data and functions into classes, enhancing clarity and structure in your codebase.

Lastly, encapsulation safeguards the integrity of data by effectively reducing the chances of unintentional data manipulation.

Python Class

Syntax for Class Definition

class ClassName:
   # Statement-1
   .
   .
   .
   # Statement-N

Creating an Empty Class in Python

class MyClass:
    pass

In the example above, MyClass is an empty class. It doesn't have any attributes or methods defined within it. It's often used as a starting point for creating more complex classes by adding attributes and methods later.

Here's a breakdown of the code:

  • class: This keyword is used to define a class in Python.

  • MyClass: This is the name of the class. You can choose any valid identifier as the class name.

  • pass: The pass statement is a placeholder statement that does nothing. It's used here because Python requires at least one statement inside a code block, even if the block is intended to be empty. In this case, it's used to create an empty class.

Python Objects

Some points on Python objects

In Python, an object is an instance of a class. Here are some points:

  • State: The attributes of an object represent the state. The properties of an object depends on the state.

  • Behavior: The methods of an object represent the behavior. The response of an object to other objects reflects on this. 

  • Identity: It provides a unique name to an object and helps one object to interact with other objects.

Objects Definition Syntax

This syntax create an object named obj of the class Cat:

obj = Cat()
  • Cat(): This is the name of the class. You can choose any valid identifier as the class name.

  • obj: This is the name of the object.

Creating an Object

obj = MyClass()

The __init__ Method in Python

In Python, __init__() is a special method that is called when an object is created from a class. It is used to initialize the attributes of the object. The __init__() method takes at least one argument, which is usually named self. This argument refers to the object being created.

Here’s an example of how to define a class with an __init__() method:

class MyClass:
    def __init__(self, arg1, arg2):
        self.arg1 = arg1
        self.arg2 = arg2

In this example, MyClass has two attributes, arg1 and arg2, which are initialized in the __init__() method.

Creating a Class and Object with Class and Instance Attributes 

Code:

class Car:
    # Class attribute
    manufacturer = "Unknown"
    def __init__(self, model, year):
        # Instance attributes
        self.model = model
        self.year = year
    def display_info(self):
        print(f"This car is a {self.year} {self.manufacturer} {self.model}")
# Creating objects of the Car class
car1 = Car("Civic", 2022)
car2 = Car("Accord", 2023)
# Accessing instance attributes
print(f"Car 1: {car1.year} {car1.manufacturer} {car1.model}")
print(f"Car 2: {car2.year} {car2.manufacturer} {car2.model}")
# Accessing class attribute
print(f"All cars are manufactured by {Car.manufacturer}")
# Modifying class attribute (applies to all instances)
Car.manufacturer = "Honda"
# Updated class attribute
print(f"Now, all cars are manufactured by {Car.manufacturer}")
# Calling instance method
car1.display_info()
car2.display_info()

Creating Classes and Objects With Methods 

Code:

class Cat:
attr1 = "mammal"
def __init__(self, name):
self.name = name
def speak(self):
print("My name is {}".format(self.name))
abc = Cat("abc")
xyz = Cat("xyz")
abc.speak()
xyz.speak()

Python Inheritance 

Syntax for Defining Inheritance

In Python, you define inheritance by including the name of the superclass in parentheses when defining the subclass. For example:

class Subclass(Superclass):
       # Subclass attributes and methods

Types of Inheritance

  • Single Inheritance: Single-level inheritance helps a derived class to inherit the characteristics present in the single-parent class.

  • Multilevel Inheritance: Multilevel inheritance helps a derived class to inherit the properties from the immediate parent class. This in turn helps to inherit properties from his parent class. 

  • Hierarchical Inheritance: Hierarchical-level inheritance helps in enabling more than one derived class to inherit the properties from a parent class.

  • Multiple Inheritance: Multiple-level inheritance helps in enabling one derived class to inherit the properties from more than one base class.

Inheritance in Python Example

Code:

class P(object):
def __init__(self, name, idnumber):
self.name = name
self.idnumber = idnumber
def display(self):
print(self.name)
print(self.idnumber)
def details(self):
print("My name is {}".format(self.name))
print("IdNumber: {}".format(self.idnumber))
class Emp(P):
def __init__(self, name, idnumber, salary, post):
self.salary = salary
self.post = post
P.__init__(self, name, idnumber)
def details(self):
print("My name is {}".format(self.name))
print("IdNumber: {}".format(self.idnumber))
print("Post: {}".format(self.post))
x = Emp('Rakesh', 786013, 300000, "Employee")
x.display()
x.details()

Python Polymorphism 

Polymorphism in Python Example

Code:

class Bird:
def introduction(self):
print("There are many types of birds.")
def fly(self):
print("Most of the birds can fly but some cannot.")
class Pigeon(Bird):
def fly(self):
print("Pigeon can fly.")
class Emu(Bird):
def fly(self):
print("Emu cannot fly.")
obj_bird = Bird()
obj_spr = Pigeon()
obj_ost = Emu()
obj_bird.introduction()
obj_bird.fly()
obj_spr.fly()
obj_ost.fly()

Python Encapsulation 

Encapsulation in Python Example

Code:

class Student:
    def __init__(self, name, age):
        self.__name = name  # Private attribute
        self.__age = age    # Private attribute
    # Getter methods to access private attributes
    def get_name(self):
        return self.__name
    def get_age(self):
        return self.__age
    # Setter methods to modify private attributes
    def set_name(self, name):
        self.__name = name
    def set_age(self, age):
        if 0 <= age <= 120:  # Valid age range
            self.__age = age
        else:
            print("Invalid age")
    def display_student_info(self):
        print(f"Name: {self.__name}, Age: {self.__age}")
# Create a Student object
student1 = Student("Alice", 20)
# Access private attributes using getter methods
print("Student name:", student1.get_name())
print("Student age:", student1.get_age())
# Modify private attributes using setter methods
student1.set_name("Bob")
student1.set_age(22)
# Display student information
student1.display_student_info()

Data Abstraction 

Some points on Python Abstraction

Abstraction is another fundamental concept in object-oriented programming (OOP) and plays a significant role in Python. Here are some key points on Python abstraction:

  • Abstract Classes: Python supports abstract classes, which cannot be instantiated directly. Abstract classes define a common interface but leave the implementation details to concrete subclasses. You can create abstract classes using the abc module.

  • Interfaces: While Python doesn't have a formal interface keyword like some other languages, it allows you to define interfaces implicitly through abstract classes or by documenting the expected methods that classes should implement. This promotes a level of abstraction by defining a contract for classes to adhere to.

  • Method Overriding: Abstraction enables method overriding, allowing subclasses to provide their own implementation of methods defined in a superclass. This is a form of abstraction that allows for polymorphism and code reuse.

  • Encapsulation and Abstraction: Encapsulation and abstraction often go hand in hand. Encapsulation hides the internal details of a class, while abstraction simplifies the interface to make it more user-friendly.

  • Data Hiding: Abstraction encourages data hiding, where you control access to class attributes (data) by marking them as private (e.g., with double underscores) and providing getter and setter methods for controlled access.

  • Real-World Examples: Abstraction is crucial in modeling real-world systems. For example, in a car simulation program, you might have an abstract class "Vehicle" with attributes like "speed" and methods like "accelerate" and "brake," allowing you to create concrete subclasses like "Car" and "Truck."

  • Code Reusability: Abstraction promotes code reusability by defining common interfaces and behaviors that can be shared across different classes and projects.

  • Complexity Management: Abstraction helps manage complexity in large software projects by breaking them down into smaller, more manageable components. 

Syntax for Defining Abstract Methods

from abc import ABC, abstractmethod
class Shape(ABC):  # Abstract base class
    @abstractmethod
    def area(self):
        pass
class Circle(Shape):
    def __init__(self, radius):
        self.radius = radius
    def area(self):
        return 3.14 * self.radius * self.radius
class Rectangle(Shape):
    def __init__(self, length, width):
        self.length = length
        self.width = width
    def area(self):
        return self.length * self.width

In this example, the Shape class is an abstract base class with an abstract method area. Concrete subclasses like Circle and Rectangle must implement the area method, enforcing abstraction.

Conclusion

Python's OOP empowers developers with a structured approach to software design, ensuring efficient code organization and flexibility. By mastering these principles, developers unlock the potential to craft sophisticated, modular, and adaptable software solutions.

FAQs

1. Why is OOP beneficial in Python?

OOP enhances code reusability and simplifies working with larger projects. Using classes, developers can avoid redundant code and define structures once for multiple uses.

2. What is the difference between class and object in Python?

A class is a blueprint defining attributes and methods, while an object is an instance of that class with specific data values.

3. What are the fundamental principles of OOP in Python?

The fundamental principles of OOP in Python are Inheritance, Polymorphism, Encapsulation, and Abstraction.

Leave a Reply

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