> ## Documentation Index
> Fetch the complete documentation index at: https://docs.syntblaze.com/llms.txt
> Use this file to discover all available pages before exploring further.

# Python Class

A class in Python is a user-defined blueprint or prototype from which objects are instantiated. It acts as a logical grouping of data (attributes) and functions (methods) that manipulate that data, providing a mechanism for bundling state and behavior together under a single, isolated namespace.

When a class is defined, it creates a new type, allowing for the creation of multiple instances of that type. Each class instance can maintain its own state independently of other instances.

```python theme={"dark"}
class ClassName:
    """Optional class docstring."""
    
    class_attribute = "Shared across all instances"

    def __init__(self, parameter):
        self.instance_attribute = parameter

    def instance_method(self):
        return self.instance_attribute
```

## Core Components

**1. Instantiation and the `__init__` Method**
Object creation in Python involves two steps: `__new__` (which allocates memory) and `__init__` (which initializes the state). Developers typically only override `__init__`. It is automatically invoked when the class is instantiated.

```python theme={"dark"}
class Developer:
    def __init__(self, language):
        self.language = language  # Instance attribute initialization


# Instantiation
dev = Developer("Python")
```

**2. The Instance Reference Parameter**
Unlike some object-oriented languages, Python requires explicit declaration of the instance reference in method signatures. By convention, this first parameter is named `self`. It binds the method to the specific instance calling it, allowing access to the instance's attributes and other methods.

**3. Attributes**
Python classes utilize two distinct scopes for attributes:

* **Instance Attributes:** Bound to a specific object instance. Defined within methods (usually `__init__`) using the instance reference (e.g., `self.attribute_name`).
* **Class Attributes:** Bound to the class itself. Defined directly beneath the class declaration. They are shared across all instances of the class unless shadowed by an instance attribute of the same name.

```python theme={"dark"}
class Server:
    protocol = "HTTP"  # Class attribute

    def __init__(self, ip):
        self.ip = ip   # Instance attribute
```

## Encapsulation and Access Control

Python does not enforce strict access modifiers at the compiler level. Instead, it relies on naming conventions and name mangling to handle encapsulation and access control:

* **Public:** Attributes and methods are public by default and can be accessed from anywhere.
* **Protected (`_` prefix):** A single leading underscore (e.g., `_internal_state`) indicates that an attribute or method is intended for internal use within the class and its subclasses. This is strictly a convention and is not enforced by the Python interpreter.
* **Private (`__` prefix):** A double leading underscore (e.g., `__private_state`) invokes name mangling. The interpreter alters the attribute name to include the class name (e.g., `_Account__private_state`), preventing accidental access or overriding by subclasses.

```python theme={"dark"}
class Account:
    def __init__(self):
        self.public_data = "Accessible"
        self._protected_data = "Internal use convention"
        self.__private_data = "Name mangled"
```

## Method Types

Python supports three primary types of methods within a class, distinguished by decorators and their parameter signatures.

**Instance Methods**
The default method type. They require an explicit first parameter to serve as the instance reference (conventionally named `self`). They can access and modify both instance state and class state.

**Class Methods (`@classmethod`)**
Bound to the class rather than the instance. They take an explicit first parameter that references the class itself (conventionally named `cls`). They can modify class state that applies across all instances but cannot modify specific instance state.

**Static Methods (`@staticmethod`)**
Bound to the class namespace but do not take an implicit first argument for the instance or the class. They cannot modify object or class state and behave like standard functions encapsulated within the class namespace.

```python theme={"dark"}
class Database:
    connection_count = 0

    def __init__(self):
        self.connected = False

    def connect(self): # Instance Method
        self.connected = True

    @classmethod
    def increment_connections(cls): # Class Method
        cls.connection_count += 1

    @staticmethod
    def validate_uri(uri): # Static Method
        return uri.startswith("db://")
```

## Magic (Dunder) Methods

Classes can implement special methods surrounded by double underscores (e.g., `__str__`, `__len__`, `__eq__`). These "dunder" methods allow classes to define how they interact with built-in Python operations, such as arithmetic operators, iteration, and string representation.

```python theme={"dark"}
class Vector:
    def __init__(self, x, y):
        self.x = x
        self.y = y

    def __add__(self, other):
        # Defines behavior for the '+' operator
        return Vector(self.x + other.x, self.y + other.y)

    def __repr__(self):
        # Defines the official string representation
        return f"Vector({self.x}, {self.y})"
```

## Inheritance and MRO

A class can inherit attributes and methods from one or more parent classes. Python supports multiple inheritance. The order in which Python resolves methods and attributes in an inheritance hierarchy is determined by the Method Resolution Order (MRO), accessible via the `__mro__` attribute or `mro()` method.

```python theme={"dark"}
class BaseAPI:
    def fetch(self):
        pass

class RestAPI(BaseAPI):
    def fetch(self):
        super().fetch() # Delegates to the parent class method
        return "JSON data"
```

<div
  style={{ 
display: "flex", 
justifyContent: "space-between", 
alignItems: "center", 
maxWidth: "754px", 
padding: "1rem 0",
marginBottom: "24px"
}}
>
  <span style={{ fontWeight: "bold", fontSize: "1.25rem", color: "var(--tw-prose-headings)", fontFamily: "Inter, ui-sans-serif, system-ui, sans-serif" }}>Tired of Poor Python Skills? Fix That With Deep Grasping!</span>

  <a
    href="https://syntblaze.com"
    target="_blank"
    style={{ 
  marginLeft: "24px",
  textDecoration: "none", 
  backgroundColor: "#007AFF",
  color: "#ffffff", 
  padding: "6px 16px", 
  borderRadius: "16px",
  fontSize: "0.9rem",
  fontWeight: "600",
  textAlign: "center",
  transition: "background-color 0.2s ease"
}}
  >
    Learn More
  </a>
</div>

<div style={{ display: "flex", gap: "12px", flexWrap: "wrap" }}>
  <img src="https://mintcdn.com/syntblazellc/-L0ums_2lctDSZ1l/images/skill-tracking.png?fit=max&auto=format&n=-L0ums_2lctDSZ1l&q=85&s=b9b0305c93bb501c9e767b5c76c88835" style={{ width: "30%", minWidth: 60 }} width="621" height="1344" data-path="images/skill-tracking.png" />

  <img src="https://mintcdn.com/syntblazellc/23tyuOzaWS88qFlc/images/nuggets.png?fit=max&auto=format&n=23tyuOzaWS88qFlc&q=85&s=c86c80197299762989e9b882419b2109" style={{ width: "30%", minWidth: 60 }} width="621" height="1344" data-path="images/nuggets.png" />

  <img src="https://mintcdn.com/syntblazellc/-L0ums_2lctDSZ1l/images/bite-sized-exercises.png?fit=max&auto=format&n=-L0ums_2lctDSZ1l&q=85&s=a65f9a38c37ff28ab73ed783c53c60e3" style={{ width: "30%", minWidth: 60 }} width="621" height="1344" data-path="images/bite-sized-exercises.png" />
</div>

<div style={{ display: "flex", gap: "12px", flexWrap: "wrap", marginTop: "12px" }}>
  <img src="https://mintcdn.com/syntblazellc/-L0ums_2lctDSZ1l/images/mastery-chain.png?fit=max&auto=format&n=-L0ums_2lctDSZ1l&q=85&s=748a1763454713e679260fbb95f154a2" style={{ width: "30%", minWidth: 60 }} width="621" height="1344" data-path="images/mastery-chain.png" />

  <img src="https://mintcdn.com/syntblazellc/-L0ums_2lctDSZ1l/images/element-previews.png?fit=max&auto=format&n=-L0ums_2lctDSZ1l&q=85&s=242f61448ff5dd6deaaab2dccc13b507" style={{ width: "30%", minWidth: 60 }} width="621" height="1344" data-path="images/element-previews.png" />

  <img src="https://mintcdn.com/syntblazellc/-L0ums_2lctDSZ1l/images/element-explanations.png?fit=max&auto=format&n=-L0ums_2lctDSZ1l&q=85&s=cf0fc1c31f9cd0fc26716781be05fbc9" style={{ width: "30%", minWidth: 60 }} width="621" height="1344" data-path="images/element-explanations.png" />
</div>
