Python Track · Part 7 of 9

Object-Oriented Programming (OOP) in Python

Python
OOP
Learn classes and objects, inheritance, polymorphism, encapsulation, and method overriding and overloading in Python.
Author

Gujuri Alekha

Published

Oct 20, 2024

Object-Oriented Programming (OOP) is a programming paradigm that revolves around the concept of objects. In Python, everything is an object, and OOP principles are used to model real-world entities and their interactions in a more organized and maintainable way.

7.1 Classes and Objects

  • Class: A class is a blueprint or template for creating objects. It defines the attributes (data members) and methods (functions) that objects of that class will have. Classes help organize and structure code by grouping related data and behavior.
  • Object: An object is an instance of a class. It is a concrete instantiation of the class, and it has its own set of attributes and can perform actions defined by the class methods.
Show code
# define  a class

class Dog:
    def __init__(self, name):
        self.name = name

    def bark(self):
        return f"{self.name} says Woof!"

# Creating objects of the Dog class
dog1 = Dog("Buddy")
dog2 = Dog("Charlie")

print(dog1.bark())  # Output: Buddy says Woof!
print(dog2.bark())  # Output: Charlie says Woof!
Buddy says Woof!
Charlie says Woof!

7.2 Inheritance and Polymorphism

  • Inheritance: Inheritance is a mechanism that allows you to create a new class (subclass or derived class) based on an existing class (base class or parent class). The subclass inherits attributes and methods from the base class, which promotes code reuse and allows you to extend or modify the behavior of the base class.
  • Polymorphism: Polymorphism means that objects of different classes can be treated as objects of a common base class. It allows you to use a single interface to represent different types of objects. Polymorphism is often achieved through method overriding and overloading.
Show code
class Animal:
    def speak(self):
        pass

class Dog(Animal):
    def speak(self):
        return "Woof!"

class Cat(Animal):
    def speak(self):
        return "Meow!"

def animal_sound(animal):
    return animal.speak()

dog = Dog()
cat = Cat()

print(animal_sound(dog))  # Output: Woof!
print(animal_sound(cat))  # Output: Meow!
Woof!
Meow!

7.3 Encapsulation and Data Hiding

  • Encapsulation: Encapsulation is the practice of bundling the data (attributes) and methods (functions) that operate on the data within a single unit, i.e., the class. It restricts access to some of the object’s components, making them private and only accessible through well-defined interfaces (getters and setters).
  • Data Hiding: Data hiding is a specific aspect of encapsulation where you hide the implementation details of an object’s attributes from the outside world. In Python, you can use underscores to indicate private attributes and methods (e.g., _private_var).
Show code
class BankAccount:
    def __init__(self, balance):
        self._balance = balance  # Using a single underscore to indicate it's semi-private

    def deposit(self, amount):
        if amount > 0:
            self._balance += amount

    def withdraw(self, amount):
        if amount > 0 and amount <= self._balance:
            self._balance -= amount

    def get_balance(self):
        return self._balance

account = BankAccount(1000)
account.deposit(500)
account.withdraw(200)
print(account.get_balance())  # Output: 1300
1300

7.4 Method Overriding and Overloading

  • Method Overriding: Method overriding allows a subclass to provide a specific implementation for a method that is already defined in its superclass. This enables the subclass to change or extend the behavior of the inherited method.
  • Method Overloading (Not Explicitly Supported in Python): Python does not support method overloading in the traditional sense as some other languages do (e.g., Java). In Python, you can define multiple methods with the same name in a class, but only the latest one defined will be used. However, you can achieve similar behavior by using default arguments and variable-length argument lists.
Show code
class Animal:
    def speak(self):
        return "Some generic sound"

class Dog(Animal):
    def speak(self):
        return "Woof!"

dog = Dog()
print(dog.speak())  # Output: Woof!
Woof!
Show code
class Calculator:
    def add(self, a, b):
        return a + b

    def add(self, a, b, c):
        return a + b + c

calc = Calculator()
print(calc.add(2, 3, 4))  # Output: 9
9

Citation

BibTeX citation:
@online{alekha2024,
  author = {Alekha, Gujuri},
  title = {Object-Oriented {Programming} {(OOP)} in {Python}},
  date = {2024-10-20},
  url = {https://gujurialekha.github.io/blog/python/07-python-object-oriented-programming.html},
  langid = {en}
}