+91 81900 98289

Python __init__ Method

This Python __init__ Method lesson is for a beginner. Read the short notes, run each example, then change one name or number and run it again.

__init__ runs when the object is created. Use it to store the starting attributes. It does not return the new object. Python does that.

Arguments after self come from the call. Batch(\"Python\", 24) passes those two values.

Example 1: Start here

Forgetting self on an attribute creates a local variable that disappears when __init__ ends.

class Batch: # a template for objects def __init__(self, topic, seats): # runs when you create the object self.topic = topic # store this on the object self.seats = seats # store this on the object print(Batch("SQL", 20).seats)

Example 2: Required setup

__init__ runs automatically when you call the class.

class Course: # a template for objects def __init__(self, title, seats): # runs when you create the object self.title = title # store this on the object self.seats = seats # store this on the object print(Course("Python", 24).seats)

Example 3: A default in init

A default lets the caller omit seats.

class Course: # a template for objects def __init__(self, title, seats=20): # runs when you create the object self.title = title # store this on the object self.seats = seats # store this on the object print(Course("Python").seats)

Example 4: Validate in init

Fix bad values before they are stored on the object.

class Course: # a template for objects def __init__(self, seats): # runs when you create the object if seats < 0: # run the indented lines only when this is true seats = 0 # a whole number self.seats = seats # store this on the object print(Course(-3).seats)
Forgetting self on an attribute creates a local variable that disappears when __init__ ends.
Call Now 81900 98289