__init__ & Attributes
The __init__ method sets up each object's data attributes.
Syntax
def __init__(self, name):
self.name = nameThe __init__ method is the constructor. Python calls it automatically when you create an object, letting you set up its starting data.
self and attributes
The first parameter, self, refers to the object being created. You store data on it as attributes, like self.name = name.
Example
class Dog:
def __init__(self, name, age):
self.name = name
self.age = age
rex = Dog('Rex', 3)
print(rex.name)
print(rex.age)
# Output:
# Rex
# 3When to use it
- A User class uses __init__ to set name, email, and created_at when a new user registers.
- A Vector class initialises x, y, and z components so every instance starts in a defined state.
- A Config class stores all settings as instance attributes, defaulting missing values in __init__.
More examples
Basic __init__ with attributes
Defines __init__ to receive arguments and store them as instance attributes on self.
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
alice = Person('Alice', 30)
print(alice.name, alice.age) # Alice 30Default values in __init__
Uses default parameter values in __init__ so callers can omit arguments they want to keep default.
class Connection:
def __init__(self, host='localhost', port=5432, timeout=30):
self.host = host
self.port = port
self.timeout = timeout
conn = Connection()
print(conn.host, conn.port) # localhost 5432
custom = Connection('db.example.com', 5433)
print(custom.host) # db.example.comComputed attribute in __init__
Computes a derived attribute (invoice_id) and captures the current date inside __init__.
import datetime
class Invoice:
def __init__(self, amount):
self.amount = amount
self.created_at = datetime.date.today()
self.invoice_id = f'INV-{id(self) % 10000:04d}'
inv = Invoice(299.00)
print(inv.invoice_id, inv.created_at, inv.amount)
Discussion