OOP & classes
Classes, instances, methods, dataclasses, and object-oriented design in Python.
How to Build a Class Method Alternative Constructor from Dict in Python
Use a classmethod alternative constructor to build a Book instance from a dictionary with sensible defaults.
class Book:
def __init__(self, title, author, pages):
self.title = title
self.author = author
self.pages = pages
@classmethod
def from_dict(cls, data):
"""Alternative constructor that builds a Book from a dictionary."""
return cls(
title=data["title"],
…
How to Define Dataclass Field Defaults in Python
Implement a Python dataclass with default values for simple fields and default factories for mutable collections.
from dataclasses import dataclass, field
from typing import List
@dataclass
class Product:
name: str
price: float = 0.0
quantity: int = 0
tags: List[str] = field(default_factory=list)
metadata: dict = field(default_factory=dict)
if __name__ == "__main__":
p1 = Product("Laptop", 999.99, 5)
…
Browse by section
Each section groups closely related Python snippets.
OOP & classes — Python code examples
What you will find here
This page collects oop & classes snippets — short, copy-ready Python you can paste into our free online IDE and run without installing anything. Each sample includes a plain-English explanation and the full source code.
Samples vs tutorials and challenges
Samples are quick reference — one concept per page. For step-by-step teaching, use our Python tutorials. To test yourself, try quizzes or coding challenges. Clean up style with the Python formatter.