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

推荐订阅源

F
Fortinet All Blogs
MyScale Blog
MyScale Blog
Microsoft Security Blog
Microsoft Security Blog
量子位
B
Blog
aimingoo的专栏
aimingoo的专栏
Apple Machine Learning Research
Apple Machine Learning Research
阮一峰的网络日志
阮一峰的网络日志
The GitHub Blog
The GitHub Blog
T
The Exploit Database - CXSecurity.com
N
News | PayPal Newsroom
Cloudbric
Cloudbric
A
About on SuperTechFans
AI
AI
Hacker News: Ask HN
Hacker News: Ask HN
S
Schneier on Security
Recent Commits to openclaw:main
Recent Commits to openclaw:main
cs.CL updates on arXiv.org
cs.CL updates on arXiv.org
C
Cyber Attacks, Cyber Crime and Cyber Security
L
LINUX DO - 最新话题
T
The Blog of Author Tim Ferriss
Simon Willison's Weblog
Simon Willison's Weblog
有赞技术团队
有赞技术团队
H
Heimdal Security Blog
J
Java Code Geeks
大猫的无限游戏
大猫的无限游戏
D
Docker
Security Archives - TechRepublic
Security Archives - TechRepublic
N
News and Events Feed by Topic
IT之家
IT之家
Know Your Adversary
Know Your Adversary
N
Netflix TechBlog - Medium
T
Tailwind CSS Blog
B
Blog RSS Feed
C
Cybersecurity and Infrastructure Security Agency CISA
C
Cisco Blogs
博客园 - 叶小钗
美团技术团队
钛媒体:引领未来商业与生活新知
钛媒体:引领未来商业与生活新知
H
Hackread – Cybersecurity News, Data Breaches, AI and More
L
LangChain Blog
The Hacker News
The Hacker News
Y
Y Combinator Blog
I
Intezer
The Register - Security
The Register - Security
F
Full Disclosure
V
V2EX
freeCodeCamp Programming Tutorials: Python, JavaScript, Git & More
Last Week in AI
Last Week in AI
Martin Fowler
Martin Fowler

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 Common SOC 2 Failures (Real World) Stop Vibe-Checking Your AI App: A Practical Guide to Evals How to Use SonarQube and SonarScanner Locally to Level Up Your Code Quality Your Next To-Do App Is Dead — I Replaced Mine with an OpenClaw AI Sign a Nostr event in 60 lines of Python using coincurve — no nostr-sdk, no nbxplorer, no rust toolchain ITGC Audit Explained Like You’re in Big 4 Patch Tuesday abril 2026: Microsoft parcha 163 vulnerabilidades y un zero-day en SharePoint Stop scraping everything: a better way to track competitor price changes Listing on MCPize + the Official MCP Registry while routing payments OUTSIDE the marketplace — how I kept 100% of my x402 revenue Building an AI-Powered Risk Intelligence System Using Serverless Architecture Why We Ripped Function Overloading Out of Our AI Toolchain Testing AI-Generated Code: How to Actually Know If It Works SaaS Churn Is Killing Your Business. Here Is What to Do About It (Without a Support Team) The Speed of AI Is No Longer Linear - And Self-Improving Models Are Why How to Implement RBAC for MCP Tools: A Practical Guide for Engineering Teams From Standard Quote to Persuasive Proposal: AI Automation for Arborists I built a CLI that scaffolds complete multi-tenant SaaS apps Axios CVE-2025–62718: The Silent SSRF Bug That Could Be Hiding in Your Node.js App Right Now The dashboard that ended our friendship Data Pipelines Explained Simply (and How to Build Them with Python) The Hidden Cost of AI Systems Nobody Talks About. undefined vs undeclared, and how typeof behaves Switching from file-based jobs to NATS/Kafka in Rust without changing code io_uring Adventures: Rust Servers That Love Syscalls Why Agentic AI is Killing the Traditional Database The POUR principles of web accessibility for developers and designers Quantum Neural Network 3D — A Deep Dive into Interactive WebGL Visualization How To Install Caveman In Codex On macOS And Windows Automation Pipeline Reliability: Why Your Workflow Breaks When Nobody Is Watching I Built an 'Open World' AI Coding Agent — It Works From ANY Folder From Freelancing to Product: A Tech Service Company's SaaS Transformation China's AI Giants: Adding Tencent Hunyuan & ByteDance Doubao to AI University (74 Providers) On the Vibe Coders and Their Lies clerk: Auto-Summarize Your Claude Code Sessions AI Weekly — 2026/04/10–04/17 | The Model Lockdown Is Here, but the Toolchain Is the Real Battleground AI 週報 — 2026/04/10–2026/04/17 模型封鎖潮來了,但工具鏈才是真戰場 Maybe this is how Open-Source apps are born... 🚀 Fine-Tune LLMs with LoRA and QLoRA: 2026 Guide tRPC v11 + Next.js App Router: End-to-End Type Safety Without the Boilerplate ShadCN UI in 2026: Why I Stopped Installing Component Libraries and Started Owning My Components SaaS Billing in React Server Components: Stripe + Supabase Without a Single `useEffect` Join our DEV Weekend Challenge — $1,000 in Prizes Across TEN winners! Submissions Due April 20 at 6:59 AM UTC. Implementing FSRS Spaced Repetition in Flutter + Supabase — Adding Memory Science to an AI Learning App "I Texted My Localhost From the Train — Claude Code Fixed the Bug Before I Got Home" I Built a Sales Prep AI and It Went Deeper Than Expected Design to Code #2: One JSON, Eleven Outputs Solving the 100M-Row Problem: A Summary Table Pattern for High-Volume Push Notification Logs Flutter Web With Wasm: What Actually Changes For Developers I Built 50 Royalty-Free Soundtracks for My Side Project in a Weekend Using AI Music Generation The Vibe Coding Security Checklist: 7 Things to Check Before You Ship Stop Letting Googlebot Guess Fix Your React App's SEO Right Desconstruindo o Streaming do LinkedIn: Como Criar um Engine de Extração de Vídeo de Alta Performance com HLS e FFmpeg (EDA Part-1) EDA (Exploratory Data Analysis) Explained With Real Life — Why Looking at Your Data Is the Most Important Step in Machine Learning Brand Relationship Management at Scale: Our 4-Touch Outreach System for 200+ Brands Why String.fromEnvironment() Might Return an Empty String in Dart JGuardrails 1.0.0 — Hardening Java LLM Apps Against Jailbreaks, Toxicity, and Prompt Injection Plan and Schedule a Full Week of Threads Content From One Claude Conversation Coding Cat Oran Ep3, Five Tables Changed Everything Updated: BFF Pattern I'm done watching freelancers get buried by 200 proposals. So I'm building the alternative. This is my first post BFS Algorithm in Java Step by Step Tutorial with Examples Tracking LLM Pricing Monthly: An Open Dataset for 22 AI Models How We Measure Content ROI on a Comparison Site: Revenue Attribution Without Perfect Data Introducing Nova AI Ops: The AI-Native Operating System for SRE Teams I built a free desktop video downloader for Windows — Grabbit How Talkie OCR Helps Vision-Impaired & Dyslexic Users Read the World Around Them VRCFaceTracking安装和iPhone面捕配置教程,有bug Even CrowdStrike Can't See Your Agents The Automation Gold Rush: What n8n Workflows and Claude Are Opening Up for Developers Right Now
Python for Beginners — Part 8: Object-Oriented Python
Ramesh S · 2026-06-23 · via DEV Community

Ramesh S

Part 8 of an 8-part beginner-friendly series on learning Python from scratch.

Congratulations — you've made it to the final part!

Everything you've learned — variables, control flow, collections, functions, file I/O, error handling — can be organized into classes and objects. This is object-oriented programming (OOP), and it's how professional Python code is written.

OOP isn't required to write working programs, but it's essential for writing code that scales, is maintainable, and professional. This final article brings everything together.

Classes and Objects

A class is a blueprint for creating objects. An object is an instance of that class. Think of a class like a cookie cutter and objects like the cookies it produces.

Defining a class

class Person:
    pass

# Create an object (instance)
person = Person()
print(person)  # <__main__.Person object at 0x...>

class Person: defines a class. person = Person() creates an object from that class.

The __init__ Method and self

The __init__ method runs automatically when you create an object. It's where you initialize the object's data.

class Person:
    def __init__(self, name, age):
        self.name = name
        self.age = age

person = Person("Ramesh", 25)
print(person.name)  # Ramesh
print(person.age)   # 25

self represents the object itself. When you write self.name = name, you're saying "this object's name attribute equals the name I was given."

Think of it this way:

  • name (parameter) is the input
  • self.name (attribute) is the object's stored data

Creating multiple objects

class Person:
    def __init__(self, name, age):
        self.name = name
        self.age = age

person1 = Person("Ramesh", 25)
person2 = Person("Priya", 23)

print(person1.name, person1.age)  # Ramesh 25
print(person2.name, person2.age)  # Priya 23

Each object is independent. person1.name is separate from person2.name.

Methods

A method is a function inside a class. Methods operate on the object's data:

class Person:
    def __init__(self, name, age):
        self.name = name
        self.age = age

    def greet(self):
        return f"Hello, I'm {self.name}"

    def have_birthday(self):
        self.age += 1

person = Person("Ramesh", 25)
print(person.greet())       # Hello, I'm Ramesh
person.have_birthday()
print(person.age)           # 26

Call methods with dot notation: person.greet(). The self parameter is passed automatically — you don't type it.

Instance vs Class Variables

Instance variables are unique to each object. Class variables are shared by all objects of that class:

class Dog:
    species = "Canis familiaris"  # Class variable

    def __init__(self, name):
        self.name = name  # Instance variable

dog1 = Dog("Buddy")
dog2 = Dog("Max")

print(dog1.name)           # Buddy (unique to dog1)
print(dog2.name)           # Max (unique to dog2)
print(Dog.species)         # Canis familiaris (shared)
print(dog1.species)        # Canis familiaris (accessible via instance too)

Use class variables for data shared by all instances. Use instance variables for data unique to each instance.

Inheritance

Inheritance lets you create a new class based on an existing class. The new class inherits methods and attributes from the parent:

class Animal:
    def __init__(self, name):
        self.name = name

    def speak(self):
        return f"{self.name} makes a sound"

class Dog(Animal):
    def speak(self):
        return f"{self.name} barks"

class Cat(Animal):
    def speak(self):
        return f"{self.name} meows"

dog = Dog("Buddy")
cat = Cat("Whiskers")

print(dog.speak())  # Buddy barks
print(cat.speak())  # Whiskers meows

Dog and Cat inherit from Animal and override the speak() method. This is called method overriding.

Using super()

Call the parent class's method with super():

class Animal:
    def __init__(self, name):
        self.name = name

    def describe(self):
        return f"{self.name} is an animal"

class Dog(Animal):
    def __init__(self, name, breed):
        super().__init__(name)  # Call parent's __init__
        self.breed = breed

    def describe(self):
        parent_desc = super().describe()  # Call parent's describe
        return f"{parent_desc} and is a {self.breed}"

dog = Dog("Buddy", "Golden Retriever")
print(dog.describe())  # Buddy is an animal and is a Golden Retriever

super() lets you access the parent class without repeating code.

Polymorphism

Polymorphism means "many shapes" — the same function name works differently depending on the object type:

class Dog:
    def speak(self):
        return "Woof!"

class Cat:
    def speak(self):
        return "Meow!"

class Cow:
    def speak(self):
        return "Moo!"

animals = [Dog(), Cat(), Cow()]

for animal in animals:
    print(animal.speak())

# Output:
# Woof!
# Meow!
# Moo!

Each animal speaks differently, but you call the same method. This is polymorphism in action.

Encapsulation

Encapsulation is the idea of bundling data and methods together, and controlling access to them. Python uses naming conventions:

  • public_attribute — accessible from outside (convention)
  • _private_attribute — intended private (convention, not enforced)
  • __really_private — name-mangled, harder to access (enforced)
class BankAccount:
    def __init__(self, balance):
        self.__balance = balance  # "Private"

    def deposit(self, amount):
        if amount > 0:
            self.__balance += amount

    def withdraw(self, amount):
        if 0 < amount <= self.__balance:
            self.__balance -= amount

    def get_balance(self):
        return self.__balance

account = BankAccount(1000)
account.deposit(500)
print(account.get_balance())  # 1500

# Can't access directly:
# print(account.__balance)  # AttributeError (name-mangled)

The double underscore (__) makes the attribute private. Access it through methods instead. This prevents accidental misuse.

Dunder Methods

Dunder methods (double underscore) are special methods Python calls automatically. Here are the most important:

__str__ and __repr__

class Person:
    def __init__(self, name, age):
        self.name = name
        self.age = age

    def __str__(self):
        return f"{self.name} ({self.age})"

    def __repr__(self):
        return f"Person('{self.name}', {self.age})"

person = Person("Ramesh", 25)
print(str(person))   # Ramesh (25) — human-readable
print(repr(person))  # Person('Ramesh', 25) — for debugging

__str__ is for end users. __repr__ is for developers.

__len__

class ShoppingCart:
    def __init__(self):
        self.items = []

    def add(self, item):
        self.items.append(item)

    def __len__(self):
        return len(self.items)

cart = ShoppingCart()
cart.add("apple")
cart.add("banana")
print(len(cart))  # 2

Now len(cart) returns the number of items.

__eq__

class Person:
    def __init__(self, name):
        self.name = name

    def __eq__(self, other):
        return self.name == other.name

person1 = Person("Ramesh")
person2 = Person("Ramesh")
print(person1 == person2)  # True (compares names)

Define how == works for your objects.

Properties and Getters/Setters

Properties let you access attributes like data, but with method-like control:

class Person:
    def __init__(self, name):
        self._name = name

    @property
    def name(self):
        return self._name

    @name.setter
    def name(self, value):
        if len(value) > 0:
            self._name = value

person = Person("Ramesh")
print(person.name)     # Ramesh (getter)
person.name = "Priya"  # Setter
print(person.name)     # Priya

The @property decorator makes name act like an attribute but run validation code.

Practical Examples

Example 1: User class

class User:
    def __init__(self, username, email):
        self.username = username
        self.email = email
        self.created_at = datetime.now()

    def __str__(self):
        return f"User({self.username})"

    def change_email(self, new_email):
        if "@" in new_email:
            self.email = new_email
        else:
            raise ValueError("Invalid email")

user = User("ramesh", "ramesh@example.com")
print(user)  # User(ramesh)
user.change_email("ramesh.new@example.com")

Example 2: Inheritance with Bank Accounts

class Account:
    def __init__(self, owner, balance):
        self.owner = owner
        self.balance = balance

    def deposit(self, amount):
        self.balance += amount

class SavingsAccount(Account):
    def __init__(self, owner, balance, interest_rate):
        super().__init__(owner, balance)
        self.interest_rate = interest_rate

    def apply_interest(self):
        self.balance *= (1 + self.interest_rate)

savings = SavingsAccount("Ramesh", 1000, 0.05)
savings.deposit(500)
savings.apply_interest()
print(savings.balance)  # 1575.0

Example 3: Polymorphism with shapes

class Shape:
    def area(self):
        raise NotImplementedError

class Circle(Shape):
    def __init__(self, radius):
        self.radius = radius

    def area(self):
        return 3.14 * self.radius ** 2

class Rectangle(Shape):
    def __init__(self, width, height):
        self.width = width
        self.height = height

    def area(self):
        return self.width * self.height

shapes = [Circle(5), Rectangle(4, 6)]
for shape in shapes:
    print(f"Area: {shape.area()}")

# Output:
# Area: 78.5
# Area: 24

Why This Matters

OOP is how professional code is organized. Without it, programs become tangled messes of functions and variables. With OOP, you group related data and behavior together into classes, making code:

  • Reusable — inheritance lets you extend existing code
  • Maintainable — encapsulation hides complexity
  • Scalable — polymorphism lets you add new types easily
  • Clear — objects represent real-world concepts

The most common beginner mistakes:

  • Forgetting self in methods
  • Confusing __init__ (constructor) with class definition
  • Not using inheritance when it makes sense
  • Overcomplicating with too many classes (start simple)
  • Breaking encapsulation with direct attribute access

Your Journey is Complete

You've now learned:

  1. Syntax and basics (Parts 1–2)
  2. Working with text and logic (Parts 3–4)
  3. Organizing data (Part 5)
  4. Organizing code (Part 6)
  5. Working in the real world (Part 7)
  6. Professional code structure (Part 8: OOP)

You have all the fundamental skills of a Python programmer. Where you go from here is up to you — web development, data science, automation, games, machine learning — Python is everywhere.

What's Next

You've completed the 8-part beginner series. From here:

  • Web development: Flask or Django frameworks
  • Data science: Pandas, NumPy, Matplotlib
  • Automation: Scripts to automate tasks
  • Games: Pygame library
  • Machine learning: Scikit-learn, TensorFlow
  • Advanced Python: Decorators, metaclasses, async/await

The fundamentals you've learned here apply to everything. Pick a project that excites you and build it.