techmore.in

Python - OOPs

What is OOP?

Object-Oriented Programming is a paradigm in Python that models code using classes and objects. It helps in structuring code for better readability, modularity, and reuse.

Classes and Objects

A class is a blueprint for creating objects. An object is an instance of a class.

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

p = Person("Alice")
print(p.name)

__init__() Method

This is a special method that is automatically called when a new object is created. It's used to initialize object attributes.

Inheritance

Inheritance allows a class to inherit attributes and methods from another class.

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

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

d = Dog()
d.speak()

Encapsulation and Abstraction

Encapsulation restricts access to certain components. Abstraction hides complex implementation details.

python
class BankAccount:
    def __init__(self, balance):
        self.__balance = balance  # Private attribute

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

    def get_balance(self):
        return self.__balance

Polymorphism

Polymorphism allows functions to use objects of different types through a common interface.

python
class Cat:
    def sound(self):
        print("Meow")

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

for animal in [Cat(), Dog()]:
    animal.sound()

Class and Static Methods

@classmethod takes the class as the first argument, @staticmethod doesn't take implicit arguments.

python
class MyClass:
    @classmethod
    def show_class(cls):
        print("This is a class method")

    @staticmethod
    def show_static():
        print("This is a static method")

Dunder (Magic) Methods

Special methods like __str__, __len__, and __add__ allow operator overloading and custom behavior.

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

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

b = Book("Python 101")
print(str(b))

Conclusion

Python's OOP features allow you to create scalable and maintainable applications. Mastering OOP is essential for advanced Python development.