Object-Oriented Programming (OOP) in Python
Master OOP Concepts with Python - By DarchumsTech
🎯 What is OOP?
Object-Oriented Programming (OOP) is a paradigm in programming that organizes code using classes and objects. It helps build reusable, modular, and efficient code.
📘 Key Concepts of OOP in Python
- Class: A blueprint for creating objects.
- Object: An instance of a class.
- Attributes: Variables that belong to a class or object.
- Methods: Functions defined inside a class.
- Encapsulation: Hiding internal details of an object.
- Inheritance: Acquiring properties and behaviors from another class.
- Polymorphism: Using a single interface for different data types.
💡 Creating a Class and Object
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
def greet(self):
return f"Hello, my name is {self.name}."
# Creating an object
p1 = Person("Alice", 30)
print(p1.greet())
🧱 Encapsulation
Encapsulation is the practice of restricting access to internal object data.
class BankAccount:
def __init__(self, balance):
self.__balance = balance # private variable
def deposit(self, amount):
if amount > 0:
self.__balance += amount
def get_balance(self):
return self.__balance
acc = BankAccount(1000)
acc.deposit(500)
print(acc.get_balance()) # Output: 1500
🧬 Inheritance
Inheritance lets one class derive from another.
class Animal:
def speak(self):
return "Animal sound"
class Dog(Animal):
def speak(self):
return "Bark"
class Cat(Animal):
def speak(self):
return "Meow"
d = Dog()
c = Cat()
print(d.speak()) # Bark
print(c.speak()) # Meow
🔁 Polymorphism
Polymorphism allows the same method name to behave differently.
def make_sound(animal):
print(animal.speak())
make_sound(Dog()) # Bark
make_sound(Cat()) # Meow
🔧 Class Methods and Static Methods
class MyClass:
count = 0
def __init__(self):
MyClass.count += 1
@classmethod
def total_instances(cls):
return cls.count
@staticmethod
def info():
return "This is a static method."
print(MyClass.info())
print(MyClass.total_instances())
✅ Best Practices in OOP
- Keep class responsibilities small (Single Responsibility Principle).
- Use proper naming conventions.
- Encapsulate your data properly.
- Re-use code through inheritance and composition.
- Use comments and docstrings for clarity.
📌 Real-World Use Case: Simple Library System
class Book:
def __init__(self, title, author):
self.title = title
self.author = author
class Library:
def __init__(self):
self.books = []
def add_book(self, book):
self.books.append(book)
def list_books(self):
for book in self.books:
print(f"{book.title} by {book.author}")
library = Library()
library.add_book(Book("1984", "George Orwell"))
library.add_book(Book("Python 101", "Michael Driscoll"))
library.list_books()
🎓 Conclusion
You've now seen the power of OOP in Python! This foundational knowledge prepares you for more advanced development including frameworks, APIs, and scalable architecture.
Comments
Post a Comment