avatarAsad iqbal

Summary

The provided web content is an introductory guide to Object-Oriented Programming (OOP) in Python, covering key concepts such as classes, objects, methods, attributes, inheritance, polymorphism, encapsulation, abstraction, composition, aggregation, and method overriding.

Abstract

The article serves as a foundational tutorial for understanding OOP principles in Python. It begins by explaining the significance of OOP in simplifying complex software development by modeling real-world entities. The author expresses enthusiasm about launching a series of tutorial articles on OOP in Python, starting with an exploration of fundamental concepts. These concepts include attributes, methods, inheritance, polymorphism, encapsulation, abstraction, composition, and aggregation, which are essential for building a strong understanding of OOP. The article also distinguishes between functions, arguments, and parameters, and illustrates how methods differ from functions by being associated with classes and objects. It further delves into the nuances of encapsulation, abstraction, and the differences between composition and aggregation. The tutorial uses code examples to demonstrate inheritance, method overriding, and polymorphism, emphasizing how these concepts allow for more flexible and maintainable code. The guide promises to pave the way for more advanced OOP topics in subsequent articles.

Opinions

  • The author is excited and motivated to share knowledge about OOP in Python, indicating a commitment to educational content.
  • OOP is presented as a powerful paradigm for managing complex codebases, suggesting its importance in modern software development.
  • The use of real-world analogies, such as comparing a University to Departments and a Car to Wheels, indicates a preference for relatable examples to explain abstract programming concepts.
  • Encapsulation and abstraction are highlighted as critical OOP features for protecting data and simplifying the interface for users, reflecting a value for clean and secure code design.
  • The distinction between composition and aggregation is emphasized to clarify how objects can be related and managed within a program, showing an attention to detail in explaining OOP relationships.
  • The article concludes with a promise of continuation, suggesting a comprehensive approach to teaching OOP in Python and an anticipation of reader engagement.

OOP in Python🐍: Guide to Key Terms and Concepts (Part-1)

Essential terms of Object-Oriented Programming (OOP) in Python

Object-Oriented Programming (OOP) is a programming paradigm that uses objects and classes to create models based on the real world✨. It simplifies complex software development problems by breaking them down into smaller, manageable pieces. With this importance in mind, I am excited to launch a series of tutorial articles📝 on OOP in Python🐍.

In the first article we will explor the fundamental OOP concepts, including attributes, methods, inheritance, polymorphism, encapsulation, abstraction, composition, and aggregation. This foundation will set the stage for exploring advanced topics in future articles.

Photo by cottonbro studio

Introduction to OOP in Python

Python is a high-level, object-oriented language that allow the building and manipulation of objects, making it an excellent choice for complex programming projects. At its core, Object-Oriented Programming (OOP) is a paradigm that helps structure and manage complex codebases by modeling real-world entities using classes and objects.

In OOP, a class is a blueprint or template that defines the properties and behaviors of an object. An object, on the other hand, is an instance of a class, possessing its own set of attributes (data) and methods (functions that operate on that data.

Here are the key OOP terms in Python we’ll cover:

  1. Function
  2. Arguments
  3. Parameters
  4. Methods
  5. Attributes
  6. Encapsulation
  7. Abstraction
  8. Composition
  9. Inheritance
  10. Aggregation
  11. Override Methods
  12. Polymorphism

Functions, Arguments, and Parameters

Function

A function is a block of code that performs a specific task. It is defined using the def keyword and can be called to execute the task.

  • A self-contained block of code.
  • Can be called independently, without being part of a class or object.
  • Typically returns a value.
# Function
def greet(name):
    print(f"Hello, {name}!")

# Calling the function
greet("Asad") # Output: Hello, Asad!

Arguments and Parameters

Parameters are variables listed inside the parentheses in the function definition.

  • Receive values when the function is called.
  • Are placeholders for the actual values that will be passed.

Arguments are the actual values passed to the function when it is called.

# Function with parameters
def greet(name, age):  # 'name', 'age' is a parameter
    print(f"Hello, {name}! You are {age} years old.")

# Calling 
greet("Asad", 25) # 'Asad', 25 is an argument

#Output: Hello, Asad! You are 25 years old.

Top 5 Must-read Computer Vision Books in 2024

How To Become a Computer Vision Engineer

Mastering Gradient Descent

Fine-tuning RoBERTa for Sentiment Analysis

Methods and Attributes

Methods

Methods are functions that are defined inside a class and operate on instances of that class, using the dot notation (class.method()).

class Person:
    def greet(self, name):  # Method
        print(f"Hello, {name}!")

person = Person()
person.greet("Asad")  # Output: Hello, Asad!

Attributes

Attributes are variables that belong to an instance of a class. They hold data about the object.

Here are some key points about attributes:

  • Instance attributes: belong to a specific object instance.
  • Class attributes: belong to the class itself and are shared by all instances.

Attributes can be:

  • Public: accessible from outside the class.
  • Private: accessible only within the class (denoted by a leading underscore _).
class Person:
    def __init__(self, name, age): # Constructor method
        self.name = name  # instance attribute
        self.age = age  # instance attribute

    occupation = "Unknown"  # class attribute

# Creating an object
person = Person("Asad", 25)  # Output: Asad, 25
  • name and age are Public Instance Attributes because they are defined inside the __init__ method and can be accessed directly using the object name (e.g., person.name and person.age).
  • occupation is a Public Class Attribute because it is defined outside the __init__ method and is shared by all instances of the class.
class Person:
    def __init__(self, name, age):
        self._name = name  # private instance attribute
        self.__age = age  # private instance attribute with name mangling

Encapsulation

Encapsulation is the bundling of data (attributes) and methods that operate on the data into a single unit, called a class. This helps to:

  • Hide internal implementation details
  • Protect data from external interference
  • Provide a controlled interface for accessing and modifying data
class Person:
    def __init__(self, name, age):
        self.__name = name  # Private attribute
        self.__age = age  # Private attribute

    def get_name(self):  # Getter method
        return self.__name

    def get_age(self):  # Getter method
        return self.__age

person = Person("Asad", 25)
print(person.get_name())  # Output: Asad
print(person.get_age())  # Output: 25

Abstraction

Abstraction means hiding the complex implementation details and showing only the essential features of the object.

class BankAccount:
    def __init__(self, balance):
        self.__balance = balance  # Abstracted data

    def deposit(self, amount):
        self.__balance += amount  # Abstracted control

    def get_balance(self):
        return self.__balance  # Abstracted interface

Composition

Composition is a way to combine objects or classes into more complex structures. in more simple way, Composition is a relationship between objects where one object (the container) owns collection of other objects. The contained objects are not complete without the container, and the container is responsible for their lifetime.

Example:

  • A University (container) has multiple Departments (contained objects)
  • A Car (container) has multiple Wheels (contained objects)
class Engine:
    def start(self):
        print("Engine started")

class Car:
    def __init__(self):
        self.engine = Engine()  # Composition

    def start_car(self):
        self.engine.start()  # Using contained object

my_car = Car()
my_car.start_car()  # Output: Engine started

Inheritance

Inheritance is a mechanism where one class (the subclass) inherits properties and behavior from another class (the superclass). The subclass inherits all the attributes and methods of the superclass and can also add new attributes and methods or override the ones inherited from the superclass.

Example:

  • A Dog (subclass) is an Animal (superclass) with additional attributes and methods specific to dogs
class Animal:
    def sound(self): # Method
        print('Generic sound')

class Dog(Animal): # "Inheritance" Dog class inherit from Animal class
    def sound(self): # overriding the sound method
        print('Bark')

dog = Dog()
dog.sound()

Aggregation

Aggregation is a relationship between objects where one object (the container) owns a collection of other objects, but the contained objects can exist independently of the container.

In other words, aggregation is a weaker form of composition, where the contained objects can have their own lifetime and can be shared among multiple containers.

Key differences between Aggregation and Composition:

  • Composition: Contained objects cannot exist independently of the container.
  • Aggregation: Contained objects can exist independently of the container.
class Book:
    def __init__(self, title, author):
        self.title = title
        self.author = author
    
class Library:
    def __init__(self):
        self.books = [] # aggregation
    
    def add_book(self, book):
        self.books.append(book)
        print(f'{book.title} by {book.author} added to the library')

book1 = Book('The Catcher in the Rye', 'J.D. Salinger')
library = Library()
library.add_book(book1)

book2 = Book('To Kill a Mockingbird', 'Harper Lee')
library.add_book(book2)

The Library class aggregates multiple Book objects, and each Book can exist independently of the Library.

Override Method

In object-oriented programming, an override method is a method in a subclass that has the same name, return type, and parameter list as a method in its superclass. The purpose of an override method is to provide a specific implementation for the subclass that differs from the implementation in the superclass.

When a subclass overrides a method, it means that the subclass is providing its own implementation of the method, which will be called instead of the superclass’s implementation.

class Animal:
    def sound(self):
        print('Generic sound')

class Dog(Animal):
    def sound(self): # overriding the sound method
        print('Bark')

dog = Dog()
dog.sound()

Polymorphism

Polymorphism allows methods to be used interchangeably, even though they may belong to different classes and have different implementations. In Python, polymorphism allows objects of different classes to be treated as objects of a common superclass.

Types of Polymorphism:

  • Method Polymorphism: Methods with the same name but different parameters or behaviors.
  • Operator Polymorphism: Operators (+, -, *, /, etc.) can be redefined for custom classes.
  • Function Polymorphism: Functions can be defined to work with different types of data.
# Polymorphism -> Present the same interface for different data types.

class Shape:
    def area(self):
        pass

class Circle(Shape):
    def __init__(self, radius):
        self.radius = radius
    
    def area(self): # Polymorphic method
        return (f'area of the circle is {3.14 * self.radius ** 2}')

class Square(Shape):
    def __init__(self, side):
        self.side = side
    
    def area(self): # Polymorphic method
        return (f'area of square is {self.side ** 2}')
    
shapes = [Circle(5), Square(5)]
for shape in shapes:
    print(shape.area())

# Output: area of the circle is 78.5
         # area of square is 25

Continues -> Part-II

Thanks for reading✨

Python
Python Programming
Development
Machine Learning
Deep Learning
Recommended from ReadMedium