Establish initial state
Set default attributes such as lists, counters, or configuration values when each object is created.
Python · Module
__init__ is a special method that initializes a new instance when its class is called. Arguments supplied during instantiation are passed to it, allowing each object to start with customized state.
Define __init__ on a class to customize each newly created instance. Python invokes it automatically during class instantiation, passing along the arguments supplied to the class call; the method can then assign instance attributes such as self.name.
def __init__(self, ...):| Name | Type | Description |
|---|---|---|
self | object | The instance being initialized. |
*args | object | Optional application-specific values supplied when the class is called; the page illustrates a name argument. |
The documentation page describes initialization during instantiation but does not specify a separate return value for __init__().
class User:
def __init__(self, name):
self.name = name
user = User("Ada")
print(user.name)The constructor receives the argument supplied when the class is instantiated and stores it on the new instance.
Set default attributes such as lists, counters, or configuration values when each object is created.
Accept constructor arguments so callers can create instances with different values.
Prepare instance variables used by the object's later methods.
__init__ is a special method that initializes a newly created instance. Python calls it automatically when the class is instantiated, and arguments passed to the class are forwarded to it.
Follow-up: What happens if __init__ accepts name but the class is called without it? The call raises a missing-argument TypeError.
Parameters declared by __init__ let callers customize initial state. The example stores the supplied value on the instance through an assignment such as self.name = name.
Follow-up: How can multiple instances retain different values? Assign the constructor argument to each instance's attributes; those attributes are separate per object.
A class can define __init__ with no arguments beyond self, or with additional parameters for flexible initialization. Calling the class passes those additional values to the method.
Follow-up: What should a class do when initialization needs optional data? Give the parameter a default value or accept an appropriate optional argument and initialize the instance consistently.
class instantiationinstance variablesclass variablesspecial methods