Skip to main content

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.

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.
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.
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.
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.
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.
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.
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.
class BaseAPI:
    def fetch(self):
        pass

class RestAPI(BaseAPI):
    def fetch(self):
        super().fetch() # Delegates to the parent class method
        return "JSON data"
Master Python with Deep Grasping Methodology!Learn More