# Python OOP (Classes and Objects)

1\. Concept Overview

In Python, **Object-Oriented Programming (OOP)** is centered around two fundamental constructs:

* **Class** – Blueprint defining structure and behavior
* **Object** – Instance of a class representing real-world entities

This paradigm enables structured, scalable, and maintainable system design for enterprise-grade applications.

> A class defines “what an object is and can do”; an object represents “a specific realization of that class”.

***

### 2. Defining a Class

```python
class User:
    pass
```

A class is created using the `class` keyword and typically contains:

* Attributes (data)
* Methods (functions)

***

### 3. Creating Objects (Instantiation)

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

user1 = User("Alice")
print(user1.name)
```

Object creation process:

1. Memory allocation
2. Constructor execution
3. Instance initialization

***

### 4. Constructor (`__init__`) Deep Dive

```python
class Employee:
    def __init__(self, emp_id, salary):
        self.emp_id = emp_id
        self.salary = salary
```

The constructor:

* Initializes object state
* Runs automatically when object is created
* Establishes initial invariants

***

### 5. Instance Variables vs Class Variables

```python
class Counter:
    global_count = 0

    def __init__(self):
        Counter.global_count += 1
```

| Variable Type | Scope      | Shared |
| ------------- | ---------- | ------ |
| Instance      | Per object | ❌ No   |
| Class         | Shared     | ✅ Yes  |

***

### 6. Defining Methods

```python
class Product:
    def display(self):
        return "Product info"
```

Method Types:

* Instance methods (`self`)
* Class methods (`cls`)
* Static methods

***

### 7. Instance Methods

```python
class Car:
    def __init__(self, model):
        self.model = model

    def info(self):
        return f"Car model: {self.model}"
```

Access and modify instance-specific data.

***

### 8. Class Methods

```python
class Config:
    environment = "PROD"

    @classmethod
    def env_info(cls):
        return cls.environment
```

Operate on class-level attributes.

***

### 9. Static Methods

```python
class Utility:
    @staticmethod
    def add(a, b):
        return a + b
```

Independent of instance and class state.

***

### 10. Attribute Access Control

```python
class Account:
    def __init__(self, balance):
        self.__balance = balance  # private

    def get_balance(self):
        return self.__balance
```

Encapsulation levels:

* Public → `self.balance`
* Protected → `_balance`
* Private → `__balance`

***

### 11. Object State and Behavior

```python
class Order:
    def __init__(self, order_id):
        self.order_id = order_id

    def process(self):
        return f"Order {self.order_id} processed"
```

Objects combine:

* State → data
* Behavior → methods

***

### 12. Object Lifecycle

| Phase          | Description          |
| -------------- | -------------------- |
| Creation       | Memory allocated     |
| Initialization | Constructor executed |
| Usage          | Methods invoked      |
| Destruction    | Garbage collected    |

***

### 13. Dunder (Magic) Methods

```python
class Vector:
    def __init__(self, value):
        self.value = value

    def __str__(self):
        return f"Vector({self.value})"
```

Used for:

* Operator overloading
* Custom object representation
* Special behaviors

***

### 14. Object Interaction (Collaborating Objects)

```python
class Engine:
    def start(self):
        return "Engine started"

class Car:
    def __init__(self):
        self.engine = Engine()

print(Car().engine.start())
```

Essential for modeling complex systems.

***

### 15. Enterprise Example: Domain Entity

```python
class Invoice:
    def __init__(self, invoice_id, amount):
        self.invoice_id = invoice_id
        self.amount = amount

    def generate(self):
        return f"Invoice {self.invoice_id} of {self.amount} created"
```

Used in:

* ERP systems
* Billing applications
* Accounting engines

***

### 16. Object Identity vs Equality

```python
a = User("Alice")
b = User("Alice")

print(a == b)   # False by default
print(a is b)   # False
```

Override using:

```python
def __eq__(self, other):
    return self.name == other.name
```

***

### 17. Encapsulation Pattern

```python
class SecureData:
    def __init__(self):
        self.__key = "secret"

    def access(self):
        return self.__key
```

Prevents unauthorized modification.

***

### 18. OOP Design Role in Enterprise Systems

Classes and objects define:

* Domain boundaries
* Service layers
* Business logic containers
* Data abstraction layers

They create maintainable enterprise architectures.

***

### 19. Common OOP Mistakes

* Overusing global variables
* Creating God objects
* Tight coupling
* Violation of SRP (Single Responsibility Principle)
* Poor naming conventions

***

### 20. Best Practices

* One class = one responsibility
* Prefer composition over inheritance
* Hide internal implementation
* Use meaningful class names
* Apply SOLID principles

***

### 21. Comparison: Procedural vs OOP

| Procedural       | OOP                |
| ---------------- | ------------------ |
| Function-centric | Object-centric     |
| Low scalability  | High scalability   |
| Hard to maintain | Clean architecture |

***

### 22. Architectural Value

Classes and objects allow:

* Feature modularization
* Code reuse
* System scalability
* Domain-driven design
* Team collaboration

They serve as building blocks for:

* Microservices
* SaaS products
* AI platforms
* Enterprise systems

***

### 23. OOP Design Patterns Enabled

* Factory Pattern
* Singleton Pattern
* Strategy Pattern
* Observer Pattern
* Builder Pattern

Enabled through intelligent class design.

***

### 24. Real-World Enterprise Example

```python
class UserProfile:
    def __init__(self, user_id, email):
        self.user_id = user_id
        self.email = email

    def authenticate(self):
        return f"{self.email} authenticated"
```

Basis of:

* Authentication services
* CRM systems
* Identity management platforms

***

### Summary

Python Classes and Objects provide:

* Structured data modeling
* Controlled state management
* Scalable architecture
* Reusable logic containers
* Business abstraction layers

They are the spine of enterprise-level Python applications.

***
