Tutorial Playlist
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.
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.
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.
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.
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 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 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 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 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.
class ClassName:
  # Statement-1
  .
  .
  .
  # Statement-N
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:
In Python, an object is an instance of a class. Here are some points:
This syntax create an object named obj of the class Cat:
obj = Cat()
obj = MyClass()
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.
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()
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()
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
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()
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()
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()
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:
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.
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.
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.
PAVAN VADAPALLI
Popular
Talk to our experts. We’re available 24/7.
Indian Nationals
1800 210 2020
Foreign Nationals
+918045604032
upGrad does not grant credit; credits are granted, accepted or transferred at the sole discretion of the relevant educational institution offering the diploma or degree. We advise you to enquire further regarding the suitability of this program for your academic, professional requirements and job prospects before enrolling. upGrad does not make any representations regarding the recognition or equivalence of the credits or credentials awarded, unless otherwise expressly stated. Success depends on individual qualifications, experience, and efforts in seeking employment.
upGrad does not grant credit; credits are granted, accepted or transferred at the sole discretion of the relevant educational institution offering the diploma or degree. We advise you to enquire further regarding the suitability of this program for your academic, professional requirements and job prospects before enr...