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

推荐订阅源

cs.AI updates on arXiv.org
cs.AI updates on arXiv.org
aimingoo的专栏
aimingoo的专栏
D
Docker
N
Netflix TechBlog - Medium
IT之家
IT之家
钛媒体:引领未来商业与生活新知
钛媒体:引领未来商业与生活新知
freeCodeCamp Programming Tutorials: Python, JavaScript, Git & More
宝玉的分享
宝玉的分享
美团技术团队
P
Proofpoint News Feed
奇客Solidot–传递最新科技情报
奇客Solidot–传递最新科技情报
Stack Overflow Blog
Stack Overflow Blog
The Cloudflare Blog
G
Google Developers Blog
腾讯CDC
Help Net Security
Help Net Security
Google DeepMind News
Google DeepMind News
Security Archives - TechRepublic
Security Archives - TechRepublic
Apple Machine Learning Research
Apple Machine Learning Research
L
LINUX DO - 最新话题
O
OpenAI News
博客园 - 司徒正美
Google Online Security Blog
Google Online Security Blog
H
Hacker News: Front Page
博客园 - 聂微东
Recent Commits to openclaw:main
Recent Commits to openclaw:main
Threat Intelligence Blog | Flashpoint
Threat Intelligence Blog | Flashpoint
Project Zero
Project Zero
Vercel News
Vercel News
C
CXSECURITY Database RSS Feed - CXSecurity.com
C
Check Point Blog
Application and Cybersecurity Blog
Application and Cybersecurity Blog
A
Arctic Wolf
Microsoft Security Blog
Microsoft Security Blog
cs.CV updates on arXiv.org
cs.CV updates on arXiv.org
Forbes - Security
Forbes - Security
www.infosecurity-magazine.com
www.infosecurity-magazine.com
人人都是产品经理
人人都是产品经理
大猫的无限游戏
大猫的无限游戏
S
Security @ Cisco Blogs
T
Tor Project blog
D
DataBreaches.Net
CTFtime.org: upcoming CTF events
CTFtime.org: upcoming CTF events
Spread Privacy
Spread Privacy
W
WeLiveSecurity
V2EX - 技术
V2EX - 技术
Simon Willison's Weblog
Simon Willison's Weblog
AI
AI
Security Latest
Security Latest
S
Securelist

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 __init__ Method Explained: A Beginner's Guide to OOP
Shameel Uddin · 2026-06-14 · via DEV Community

Introduction

The __init__ method helps us initialize objects automatically whenever they are created.

Instead of manually assigning data to every object, Python allows us to automate the process using the __init__ method.

The Pain Point before Python init

Imagine a simple class for a user. You create an object from that class, and then later assign attributes like name or email. That works, but it is manual.

Consider the following class

class SimpleUser:
    pass 
user = SimpleUser()
user.name = "Shameel" 
user.email = "shameel@example.com"

Here, we create an object and then manually assign attributes.

Problem

Every time we create an object, we must remember to add all required attributes manually.

For example:

user = SimpleUser()

#If we forget to assign:

user.name
user.email

Our object becomes incomplete.

This can cause errors later in the program.

Another Common Approach

Developers often create a separate method:

class SimpleUser:

    def set_data(self, name, email):
        self.name = name
        self.email = email

Usage:

user = SimpleUser()

user.set_data(
    "Shameel",
    "shameel@example.com"
)

Although this works, there is still a risk.

A developer might forget to call:

user.set_data()

and the object will remain uninitialized.

At first, this seems fine. But there is an obvious weakness. You can create the object and forget to call the setup method. Then you end up with an object that exists, but does not actually contain the data it is supposed to have.

That is exactly the kind of error-prone pattern Python__init__ is designed to avoid.

How Python init Uses "self" to Assign Attributes

Before understanding Python __init__ properly, it helps to be clear on how self works.

Inside an instance method,selfrefers to the specific object currently being worked on. So when you write something like:

self.name = name 

self.email = email

you are attaching attributes directly to that object.

So if an object is stored in a variable called user, then inside the method, self is just another reference to that same object.

Assigning values through self means the object itself now carries those values.

Nothing magical is happening. The object is simply receiving attributes throughself.

What Python init actually Is

Python __init__ is a special method used for automatic object initialization.

Its name has a special format with two underscores before and after it.

Methods written in this style are often called Dunder Methods.
Dunder is short for double underscore methods. They are special methods in Python with predefined meanings.

The__init__ method is written like any other method, but Python treats it specially. As soon as you create an object from a class Python __init__ runs automatically.

That means instead of doing this in two separate steps:

  • Create the object
  • Manually call another method to set attributes

you can do it all at the time of object creation.

How Python init Improves Object Creation

Suppose you define a User class with an __init__ method that accepts:

  • email
  • name
  • role (with a default value)

That immediately gives you a much cleaner pattern

class User:
    def __init__(self, email, name, role="user"):
        self.email = email
        self.name = name
        self.role = role

Now every time you create a user, Python automatically runs this setup logic.

So if you create an object with email and name, those values are assigned straight away. If you do not provide a role, it defaults to user. This means your object starts out complete and predictable.

Required and Optional Parameters in Python_init_

One useful thing about Python __init__ is that it lets you define which data is mandatory and which data is optional.

In the example above:

  • email is required
  • name is required
  • role is optional because it already has a default value

That means object creation itself becomes a kind of contract. Anyone creating a user must provide the important values. Optional values can still be customised when needed.

This is one of the biggest reasons Python __init__ is so useful. It forces the right information to be provided at the right time.

Using Python init for Validation

Another major benefit of Python __init__ is validation.

For example, if you expect an email address, you can check whether it contains the @ symbol before accepting it. If the format is wrong, you can stop object creation immediately.

class User:
    def __init__(self, email, name, role="user"):
        if "@" not in email:
            raise ValueError("Invalid email")

        self.email = email
        self.name = name
        self.role = role

This is powerful because it prevents invalid objects from being created in the first place.

You can also imagine stricter rules, such as:

  • Allowing only business email addresses
  • Rejecting common public domains
  • Applying company-specific signup requirements

The point is simple Python __init__ is not only for storing data. It is also the perfect place to protect the integrity of your objects.

Derived Attributes in Python init

Sometimes an object is created with one piece of data, and from that data you want to generate something extra. That is where derived attributes come in.

For example, if a user signs up with an email address, you might also want to store the email domain. Instead of asking for both separately, you can derive the domain from the email inside Python __init__

self.domain = email.split("@")[1]

If the email is something like shameel@hasab.tech, then the derived domain becomes company.com.

This is useful because:

  • It avoids repeated work elsewhere in the code
  • It keeps related logic together
  • It ensures the derived value is always available on the object

So Python __init__ can take input data and transform it into extra attributes that make the object more useful.

Setting Default Internal Attributes with Python init

Another common pattern is assigning internal defaults that every object should have, regardless of what the caller provides.

For a user object, that might mean attributes such as:

  • is_active = True
  • login_attempts = 0

These are not values the caller necessarily needs to pass in. They are part of the system's default behavior.
This makes Python__init__ a convenient place to define the starting state of each object.

Whenever a new user is created, those defaults are already in place. No extra setup is required later.

Auto-Generated Attributes in Python init

Some attributes are not provided by the user at all. They are generated automatically by the system.

Examples include:

A unique user ID A creation timestamp Some internal tracking value

This is another natural use case for Python __init__ When the object is created, these values can be generated and attached immediately.

A popular Python approach for unique identifiers is using a UUID. In real applications, this kind of auto-generated data is very common, especially for records that later connect to databases or APIs.

What happens when an object is instantiated?

This is the key thing to remember about Python __init__ it runs automatically during instantiation.

When you write something like:

user1 = User("name@company.com", "Shameel")

Python does not just create an empty object and stop there. It creates the object and then immediately calls __init__ for that object.

At that moment:

  • self refers to the newly created object
  • The provided arguments are mapped to the parameters
  • Assignments, validation, and extra logic run automatically

So the object is initialized right away, not later.

If you provide only the required values, optional ones use their defaults. If you provide a custom role, that custom value is stored instead.

A Practical Example of Python init

Here is the complete pattern all together:


class User:
    def __init__(self, email, name, role="user"):
        if "@" not in email:
            raise ValueError("Invalid email")

        self.email = email
        self.name = name
        self.role = role
        self.domain = email.split("@")[1]
        self.is_active = True
        self.login_attempts = 0

With this design, each new object gets:

  • Required data stored automatically
  • Optional data handled cleanly
  • Validation before acceptance
  • Derived attributes created instantly
  • Default internal values assigned consistently

That is the real strength of Python__init__ It centralizes the setup of an object in one reliable place.

Why Python init Beats Manual Setup Methods

Manual setup methods can work, but they depend on discipline. A person creating the object has to remember the extra step every single time.

That leads to several risks:

  • An object may be created without necessary attributes
  • Validation may be skipped accidentally
  • Default values may not be assigned consistently
  • Different parts of the code may initialize objects differently Python __init__ removes all of that uncertainty. The object cannot be properly created without passing through its initialization logic.

In other words Python __init__ makes object creation safer, cleaner, and less repetitive.

Key Python init Patterns Every Beginner Should Know

When using Python __init__ these are the most important patterns to keep in mind:

  • Basic attribute assignment Store incoming values directly on the object.
  • Validation Check that incoming data is acceptable before storing it.
  • Derived attributes Generate additional values from the provided input.
  • Internal defaults Assign standard starting values that every object should have
  • Auto-generated Values Create IDs, timestamps, or other system-generated properties.

Final takeaway on Python init

If you remember just one thing: __init__ is the automatic setup method for your objects. It is called as soon as an object is instantiated, and it exists to make sure the object starts with the right data, the right defaults, and the right checks.

So instead of creating an object first and then manually attaching everything later, Python lets you define a proper initialization process once and reuse it every time.

That is why it is such a core part of Object Oriented Programming in Python.
Stay connected with hasabTech for more information:
Website | Facebook | LinkedIn | YouTube | X (Twitter) | TikTok