Python Object-Oriented Programming (OOP) for Beginners

Learn Python Object-Oriented Programming (OOP) for beginners: classes, objects, inheritance, methods, encapsulation, and practical examples.


Object-Oriented Programming (OOP) is a programming paradigm that organizes code using classes and objects. Python supports OOP and makes it simple to create reusable, modular, and maintainable code. In this guide, we will explore Python OOP concepts step-by-step, including classes, objects, attributes, methods, inheritance, polymorphism, encapsulation, and more. By the end, you'll be able to apply OOP concepts in real projects.

1. Introduction to Object-Oriented Programming

OOP revolves around the concept of objects, which are instances of classes. A class defines a blueprint for an object, including its properties (attributes) and behaviors (methods).

1.1 Benefits of OOP

  • Reusability: Classes can be reused across multiple projects.
  • Modularity: Code is organized into independent classes.
  • Maintainability: Easy to update or extend features.
  • Abstraction: Hide internal details and show only functionality.
  • Inheritance: Create new classes based on existing ones.

2. Python Classes and Objects

2.1 Defining a Class

A class is defined using the class keyword:

class Person:
    pass  # Empty class for now

2.2 Creating Objects

Objects are instances of a class:

person1 = Person()
person2 = Person()

print(person1)
print(person2)

2.3 Attributes and the Constructor

Attributes store data about an object. The __init__ method is the constructor that initializes attributes:

class Person:
    def __init__(self, name, age):
        self.name = name
        self.age = age

person1 = Person("Alice", 25)
person2 = Person("Bob", 30)

print(person1.name, person1.age)
print(person2.name, person2.age)

3. Methods in Python Classes

Methods define the behavior of objects. The first parameter of a method is always self, which refers to the current object.

3.1 Instance Methods

class Person:
    def __init__(self, name, age):
        self.name = name
        self.age = age

    def greet(self):
        print(f"Hello, my name is {self.name} and I am {self.age} years old.")

person = Person("Alice", 25)
person.greet()

3.2 Class Methods

Class methods are shared across all instances and use the @classmethod decorator:

class Person:
    population = 0

    def __init__(self, name):
        self.name = name
        Person.population += 1

    @classmethod
    def get_population(cls):
        return cls.population

p1 = Person("Alice")
p2 = Person("Bob")
print(Person.get_population())

3.3 Static Methods

Static methods do not access instance or class attributes and use @staticmethod:

class MathHelper:
    @staticmethod
    def add(a, b):
        return a + b

print(MathHelper.add(5, 7))

4. Inheritance in Python

Inheritance allows a class (child) to acquire attributes and methods from another class (parent).

4.1 Single Inheritance

class Animal:
    def speak(self):
        print("Animal speaks")

class Dog(Animal):
    def speak(self):
        print("Dog barks")

dog = Dog()
dog.speak()

4.2 Multiple Inheritance

class Flyer:
    def fly(self):
        print("I can fly")

class Swimmer:
    def swim(self):
        print("I can swim")

class Duck(Flyer, Swimmer):
    pass

d = Duck()
d.fly()
d.swim()

4.3 Using super()

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

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

dog = Dog("Buddy", "Labrador")
print(dog.name, dog.breed)

5. Encapsulation

Encapsulation restricts access to object data using private attributes and methods. In Python, prefix _ for protected and __ for private attributes.

class Person:
    def __init__(self, name, age):
        self.__name = name  # private
        self.__age = age    # private

    def get_info(self):
        return f"Name: {self.__name}, Age: {self.__age}"

p = Person("Alice", 25)
print(p.get_info())
# print(p.__name)  # This will raise an error

6. Polymorphism

Polymorphism allows different classes to implement the same method name differently.

class Cat:
    def speak(self):
        print("Meow")

class Dog:
    def speak(self):
        print("Bark")

animals = [Cat(), Dog()]
for animal in animals:
    animal.speak()

7. Special Methods (Magic Methods)

Special methods in Python start and end with double underscores. Examples include __str__, __len__, __add__.

class Book:
    def __init__(self, title, pages):
        self.title = title
        self.pages = pages

    def __str__(self):
        return f"{self.title}, {self.pages} pages"

b = Book("Python OOP Guide", 200)
print(b)

8. Practical OOP Examples

8.1 Bank Account Class

class BankAccount:
    def __init__(self, owner, balance=0):
        self.owner = owner
        self.balance = balance

    def deposit(self, amount):
        self.balance += amount
        print(f"Deposited {amount}. New balance: {self.balance}")

    def withdraw(self, amount):
        if amount <= self.balance:
            self.balance -= amount
            print(f"Withdrawn {amount}. Remaining balance: {self.balance}")
        else:
            print("Insufficient funds")

account = BankAccount("Alice", 1000)
account.deposit(500)
account.withdraw(200)

8.2 Library System Example

class Book:
    def __init__(self, title):
        self.title = title

class Library:
    def __init__(self):
        self.books = []

    def add_book(self, book):
        self.books.append(book)

    def show_books(self):
        for book in self.books:
            print(book.title)

lib = Library()
lib.add_book(Book("Python Basics"))
lib.add_book(Book("OOP in Python"))
lib.show_books()

9. Best Practices for Python OOP

  • Use descriptive class and method names.
  • Keep classes small and focused on a single responsibility.
  • Use inheritance only when necessary.
  • Encapsulate data to prevent unintended modifications.
  • Document classes and methods using docstrings.
  • Follow PEP 8 conventions for code readability.

10. FAQs about Python OOP

What is the difference between a class and an object?

A class is a blueprint for creating objects. An object is an instance of a class containing actual data and behaviors.

What is inheritance in Python?

Inheritance allows a child class to reuse attributes and methods of a parent class.

What is encapsulation?

Encapsulation restricts access to certain parts of an object using private or protected attributes.

Can Python classes have multiple constructors?

Python does not support multiple constructors directly, but you can use default arguments or class methods.

What are magic methods?

Magic methods (special methods) are built-in methods with double underscores, like __init__ and __str__, that customize object behavior.

What is polymorphism?

Polymorphism allows different classes to implement methods with the same name differently.

Conclusion

Python OOP is a powerful paradigm that makes your code modular, reusable, and maintainable. By mastering classes, objects, inheritance, encapsulation, polymorphism, and magic methods, you can create complex programs efficiently. Practice by building real-world projects like bank accounts, library systems, or games to solidify your understanding of OOP concepts.

About the author

Prasun Barua
Prasun Barua is a graduate engineer in Electrical and Electronic Engineering with a passion for simplifying complex technical concepts for learners and professionals alike. He has authored numerous highly regarded books covering a wide range of elec…

Post a Comment