pty1
pty1
---
## Introduction
Python is an incredibly versatile language, known for its simplicity and readability. However, as
applications grow in size and complexity, it becomes essential to adopt principles that help in
managing this complexity. Object-Oriented Programming (OOP) is a programming paradigm
that organizes code into reusable, modular objects, providing an intuitive approach to
structuring programs. In Python, OOP principles allow developers to create classes, define
objects, and model real-world problems with efficiency and scalability.
This notebook will walk you through the fundamentals of OOP in Python, covering core
concepts like classes and objects, advanced principles like inheritance and polymorphism, and
some of the common patterns used in OOP design. Whether you are a beginner looking to
understand how OOP can help you write better Python code or an advanced user looking to
deepen your knowledge, this guide will provide the insights you need.
---
1
Object-Oriented Programming (OOP) is a paradigm where code is organized into objects, which
are instances of classes. This style of programming emphasizes modularity and reusability by
creating "objects" that combine data and functionality.
- **Object**: A collection of data (attributes) and methods (functions) that act on the data.
- **Class**: A blueprint that defines the structure and behavior of objects. It allows creating
multiple instances of similar objects, making code modular and reusable.
- **Reusability**: Write code that can be reused across different parts of the program.
- **Inheritance**: Create hierarchies where derived classes inherit properties of base classes.
---
A **class** is a blueprint for creating objects. Each object is an instance of a class. Let's start by
defining a simple class:
2
```python
class Animal:
self.name = name
def greet(self):
print(f"Hello, I am {self.name}")
cat = Animal("Cat")
```
- Methods are functions defined inside a class and are specific to objects created from that
class.
Attributes and methods form the data and behavior of an object, respectively.
3
```python
class Car:
# Class attribute
wheels = 4
# Instance attributes
self.make = make
self.model = model
def drive(self):
```
```python
print(car1.wheels) # Output: 4
```
---
4
## Important OOP Principles
### 1. Encapsulation
```python
class BankAccount:
if amount > 0:
self.__balance += amount
else:
print("Invalid amount")
self.__balance -= amount
else:
5
print("Insufficient balance")
def get_balance(self):
return self.__balance
```
```python
account = BankAccount(1000)
account.deposit(500)
```
### 2. Inheritance
Inheritance allows a class to inherit attributes and methods from another class, promoting code
reusability.
```python
# Base class
class Animal:
def speak(self):
print("Animal speaks")
# Derived class
6
class Dog(Animal):
def bark(self):
print("Dog barks")
# Example usage
dog = Dog()
```
### 3. Polymorphism
Polymorphism allows objects to be treated as instances of their parent class, even if their
behaviors differ.
#### Example
```python
class Bird:
def sound(self):
print("Bird chirps")
class Dog:
def sound(self):
print("Dog barks")
7
def make_sound(animal):
animal.sound()
# Example usage
sparrow = Bird()
puppy = Dog()
```
---
### 1. Abstraction
Abstraction simplifies complex reality by focusing on essential aspects, hiding irrelevant details.
```python
class Shape(ABC):
@abstractmethod
8
def area(self):
pass
class Circle(Shape):
self.radius = radius
def area(self):
```
### 2. Composition
```python
class Engine:
def start(self):
print("Engine starts")
class Car:
def __init__(self):
9
def start(self):
self.engine.start()
print("Car starts")
```
---
|------------------|----------------------------------------------------|----------------|
| Abstraction | Hiding complex details from the user | Abstract base classes |
---
Below is a more comprehensive example that brings together the concepts of classes,
inheritance, encapsulation, and polymorphism.
10
```python
class Book:
self.title = title
self.author = author
class Library:
def __init__(self):
self.books = []
self.books.append(book)
def list_books(self):
print(f"{book.title} by {book.author}")
# Example usage
library = Library()
library.add_book(book1)
11
library.add_book(book2)
library.list_books()
```
---
## Conclusion
12