Python 101 · Object Oriented Programming

Feb 20, 2016 | Tech Software

Index
Index

Basics

  • Class

    : A blueprint or template that defines the structure of properties (data) and methods (behaviors) that all objects of its type will possess.
  • Object

    : A specific instance created from a class, containing actual data for its properties and capable of performing the methods defined by its blueprint.
  • __init__()

    : A special method called a constructor that is automatically executed to initialize an object's attributes the moment it is instantiated.
  • self

    : A reference variable that represents the specific instance of the object, allowing the code to access its unique data and methods.

Encapsulation

  • Protected, _var

    : A convention indicating an internal variable that should not be accessed outside the class, though it remains technically accessible.
  • Private, __var

    : A mechanism that triggers Name Mangling, renaming the attribute to prevent direct accidental access from outside the class.
  • Getter, @property

    : Allows a method to be accessed like a regular attribute (without using parentheses).
  • Setter, @var.setter

    : Enables logic validation or data processing to be executed automatically when an attribute is modified.
The @property and @var.setter provide a Pythonic interface that encapsulates internal logic while maintaining a clean, attribute-like syntax for the user with a never-changing API.

Inheritance

  • Base/Parent Class

    : The class being inherited from, providing shared attributes and methods to be reused.
  • Derived/Child Class

    : The class that inherits from the parent, capable of keeping or overriding existing methods or adding unique new ones.
  • super()

    : A built-in function used to give the Child Class access to methods and the constructor of the Parent Class.
  • Method Resolution Order, MRO

    : The linear sequence (C3 Linearization algorithm) Python follows to search for a method or attribute across a class hierarchy, especially in cases of multiple inheritance.
  • Abstract Base Class, ABC

    : A template class that defines a set of required methods, via @abstractmethod, that all its subclasses must implement, ensuring a consistent interface while preventing the base class itself from being instantiated.
  • Mixin

    : A specialized form of multiple inheritance used to "mix in" additional behaviors to a class without being its primary parent. Mixins should be small, single-purpose, and are not intended to be instantiated on their own. Their name should end with Mixin by convention.

Dunder Methods

Short for "Double Underscore", a.k.a., Magic Methods, these are special methods that allow your custom classes to "hook" into Python's built-in behaviors, such as arithmetic, comparisons, or string formatting.
  • String Representation

    : Defines how an object 'presents' itself as a string, ensuring it is easily-readable for users __str__ and debugging-friendly for developers __repr__.
  • Arithmetic Operations

    : Operator overloading via __add__ (+), __sub__ (-), and __mul__ (*), etc., allowing custom objects work with standard mathematical syntax, making them behave like built-in numeric types.
  • Container & Sequence Protocol

    : Allowing collection behavior via __len__ (length) and __getitem__ (indexing), such that your class can be treated like a list or dictionary, allowing them to be indexed, sliced, or measured.
  • Lifecycle & Callable

    : Enabling construction & execution, like __init__ initializes an instance, __new__ (a magic class method) handles the memory allocation and returns the object (often used in Singleton), __call__ allows an instance to be executed like a function.
  • Comparison Methods

    : Allowing custom logic for standard operators like ==, <, >, enabling objects to be sorted or filtered based on specific attributes.

Miscellaneous

  • @classmethod

    : A method that receives the class itself (cls) as the first argument instead of an instance, primarily used for Factory Patterns.
  • @staticmethod

    : A method that does not receive any implicit first argument (self or cls), like a regular function living in the class's namespace for logical grouping; mostly for utility functions needing no access to class or instance data.
  • @dataclass

    : A dataclass is a class decorator that automates the generation of boilerplate code for data-oriented objects, primarily by synthesizing methods like __init__, __repr__, and __eq__ based on type hints.
  • __dict__

    : A dictionary or other mapping object used to store an object's (writable) attributes; which makes Python objects dynamic, allowing users to add or modify attributes at runtime.
The Cost of Dynamic Flexibility with __dict__
  • Memory Overhead: Every instance maintains its own hash map. To minimize collisions, these dictionaries pre-allocate extra space, leading to significant memory waste when creating many objects.
  • Performance Latency: Accessing an attribute requires a hash table lookup, which is computationally more expensive than accessing data at a fixed memory offset.
  • __slot__

    : A class-level attribute explicitly declaring allowed instance attributes, preventing the creation of a dynamic dictionary for each instance, significantly reducing memory overhead and slightly improving attribute access speed.
Usage Strategy for __slots__
  • DO: Use it when your application needs to instantiate massive quantities of objects (e.g., millions of game particles or sensor data points) to reduce memory.
  • DON'T: Use it for general scripts or when you need dynamic flexibility; it breaks the ability to add new attributes on the fly and can complicate certain types of multiple inheritance.
  • __getattr__

    : A fallback dunder method called only when an attribute is not found in the usual places, instance __dict__ or class tree. It allows you to dynamically handle missing attributes, making it perfect for creating "wrappers" or "proxies."
  • Metaclass

    : In Python, everything is an object. While a class defines how to create an instance, a metaclass defines how to create a class. By default, Python uses type as the metaclass for all classes. When you define class MyClass:, behind the scenes, Python actually executes type("MyClass", (), {}).
Why Use Metaclasses?
  • The primary purpose is to intercept and modify the class creation process. Key usage cases include:
    • Automatically adding attributes or methods to classes.
    • Enforcing coding standards, e.g., validating class naming conventions.
    • Registering classes to a global registry, as in Object-Relational Mapping (ORM) frameworks.
  • "Metaclasses are deeper magic than 99% of users should ever worry about. If you wonder whether you need them, you don't." -- Tim Peters
  • Monkey Patching (on the fly)

    : A technique used to dynamically modify or extend the behavior of existing modules, classes, or functions at runtime without altering the original source code. Primarily realized with getattr(), setattr(), hasattr(), and delattr().