惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

Apple Machine Learning Research
Apple Machine Learning Research
J
Java Code Geeks
让小产品的独立变现更简单 - ezindie.com
让小产品的独立变现更简单 - ezindie.com
freeCodeCamp Programming Tutorials: Python, JavaScript, Git & More
Last Week in AI
Last Week in AI
雷峰网
雷峰网
博客园_首页
小众软件
小众软件
美团技术团队
奇客Solidot–传递最新科技情报
奇客Solidot–传递最新科技情报
腾讯CDC
P
Proofpoint News Feed
MongoDB | Blog
MongoDB | Blog
Google DeepMind News
Google DeepMind News
MyScale Blog
MyScale Blog
U
Unit 42
The Cloudflare Blog
钛媒体:引领未来商业与生活新知
钛媒体:引领未来商业与生活新知
Microsoft Security Blog
Microsoft Security Blog
大猫的无限游戏
大猫的无限游戏
Engineering at Meta
Engineering at Meta
N
Netflix TechBlog - Medium
Microsoft Azure Blog
Microsoft Azure Blog
博客园 - 叶小钗

DEV Community

Authentication Security Deep Dive: From Brute Force to Salted Hashing (With Java Examples) Why AI Systems Don’t Fail — They Drift Spilling beans for how i learn for exam😁"Reinforcement Learning Cheat Sheet" I Replaced Chrome with Safari for AI Browser Automation. Here's What Broke (and What Finally Worked) How Python Borrows Other People's Work The $40 Architecture: Processing 1 Billion API Requests with 99.99% Uptime Vibe Coding: A Workflow Guide (From Zero to SaaS) Most webhook security guides protect the wrong side. The scary part is delivery. Headless CMS for TanStack Start: Build a Blog with Cosmic EU Age Verification App "Hacked in 2 Minutes" — What Actually Happened Comfy Cloud’s delete function does not actually remove files Running AI Models on GPU Cloud Servers: A Beginner Guide Event-driven media intelligence with AWS Step Functions and Bedrock I scored 500 AI prompts across 8 quality dimensions — here's what broke How to Call Google Gemini API from Next.js (Free Tier, No Backend Needed) The Portal Protocol: Reclaiming Human Connection in the Age of AI How to Fix Your Team's Scattered Knowledge Problem With a Self-Hosted Forum Intro to tc Cloud Functors: A Graph-First Mental Model for the Modern Cloud Designing Multi-Tenant Backends With Both Ownership and Team Access I Built a Neumorphic CSS Library with 77+ Components — Here's What I Learned PostgreSQL Performance Optimization: Why Connection Pooling Is Critical at Scale Cómo construí un SaaS multi-rubro para gestionar expensas en Argentina con FastAPI + Vue 3 🚀 I Built an Ethical Hacking Scanner Tool – Open Source Project I Replaced /usage and /context in Claude Code With a Single Statusline A Pythonic Way to Handle Emails (IMAP/SMTP) with Auto-Discovery and AI-Ready Design I Collected 8.9 Million Polymarket Price Points — Here's What I Found About How Markets Really Move EcoTrack AI — Carbon Footprint Tracker & Dashboard Everyone's Using AI. No One Agrees How. 5 self-hosted ebook managers worth trying in 2026 Building Your First AI Agent with LangChain: From Chatbot to Autonomous Assistant
From Rails to Python: Why Python Classes Feel Simpler in ...
M.T.Ramkrush · 2026-05-19 · via DEV Community

M.T.Ramkrushna

If you’re coming from Ruby or Rails, Python classes can feel surprisingly lightweight.
You still get object-oriented programming, encapsulation, reusable code, and clean architecture — but with less “magic”.

In this article, we’ll build a small real-world backend example using:

  • Python classes
  • Type hints
  • Decorators
  • Generators

And we’ll model something most developers understand instantly: an order processing system.


Real-Life Scenario

Imagine you are building a backend for:

  • an ecommerce store,
  • Food delivery system,
  • SaaS billing engine,
  • or warehouse management app.

You’ll likely have:

  • Orders
  • Customers
  • Inventory
  • Event logs

This is where Python classes become extremely practical.


Basic Python Class Example

class Order:
    def __init__(self, order_id: int, customer: str):
        self.order_id = order_id
        self.customer = customer
        self.status = "pending"

    def complete_order(self):
        self.status = "completed"

order = Order(101, "Ali")

print(order.customer)
print(order.status)

order.complete_order()

print(order.status)

Enter fullscreen mode Exit fullscreen mode

Output:

Ali
pending
completed

Enter fullscreen mode Exit fullscreen mode


Why This Feels Cleaner Than Many OOP Systems

Python removes unnecessary ceremony.

You don’t need:

  • getters/setters everywhere,
  • verbose constructors,
  • interfaces for everything,
  • complex inheritance chains.

Most backend systems only need:

  • simple models,
  • service classes,
  • utility layers.

Python excels here.


Add Type Hints for Production Readability

Now let’s make this production-friendly.

class Order:
    def __init__(self, order_id: int, customer: str):
        self.order_id: int = order_id
        self.customer: str = customer
        self.status: str = "pending"

    def complete_order(self) -> None:
        self.status = "completed"

Enter fullscreen mode Exit fullscreen mode

Why type hints matter

In large teams:

  • they improve autocomplete,
  • reduce bugs,
  • help onboarding,
  • make APIs self-documenting.

Especially useful when building:

  • FastAPI apps,
  • AI systems,
  • async services,
  • internal SDKs.

Using Decorators for Logging

Real systems need observability.

Suppose you want to log every important action.

def log_action(func):
    def wrapper(*args, **kwargs):
        print(f"Running: {func.__name__}")
        return func(*args, **kwargs)
    return wrapper

Enter fullscreen mode Exit fullscreen mode

Use it inside the class:

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

    @log_action
    def ship(self):
        print("Order shipped")

Enter fullscreen mode Exit fullscreen mode

Output:

Running: ship
Order shipped

Enter fullscreen mode Exit fullscreen mode


Real Backend Use Cases of Decorators

Decorators are heavily used in:

  • authentication,
  • rate limiting,
  • retries,
  • caching,
  • logging,
  • monitoring,
  • API routing.

Example:

@app.get("/orders")

Enter fullscreen mode Exit fullscreen mode

That FastAPI route itself is a decorator.


Generators: Secret Weapon for Large Data

Suppose your warehouse has 10 million orders.

Returning all data at once is memory-heavy.

Generators solve this elegantly.

def order_ids():
    for i in range(1, 1000000):
        yield i

Enter fullscreen mode Exit fullscreen mode

Usage:

for order_id in order_ids():
    print(order_id)

Enter fullscreen mode Exit fullscreen mode

The values are generated lazily.


Real-Life Generator Use Cases

Generators are perfect for:

  • CSV processing,
  • log streaming,
  • AI dataset pipelines,
  • Kafka consumers,
  • ETL jobs,
  • background workers.

Instead of loading everything into RAM, Python streams data efficiently.


Final Thoughts

Python classes are practical because they focus on:

  • readability,
  • maintainability,
  • developer speed.

When combined with:

  • decorators,
  • generators,
  • type hints,

you can build production-grade systems that remain surprisingly simple.

That’s one reason Python dominates:

  • AI engineering,
  • backend systems,
  • automation,
  • data infrastructure.