Python __init__()
Anonymous contributor
Published Jul 11, 2022Updated Feb 23, 2024
Contribute to Docs
The __init__() method initializes a newly created object. It is called each time a new instance of the defined class is created.
Syntax
class ClassName:
def __init__(self, param1, param2, ..., paramN):
self.param1 = param1
self.param2 = param2
self.paramN = paramN
self.default_param = value
In a class definition, instance attributes can be set within the __init__() in two ways:
- With named parameters (
param1, param2, ..., paramN) that will be required when a class instance is created. - A
default_paramand correspondingvaluecan also be defined so that every instance has access to this parameter.
Additionally, instance attributes can be added to a specific instance variable afterwards:
new_class_instance = ClassName(value1, value2, ..., valueN)
new_class_instance.specific_variable = new_value
Codebyte Example
The example below showcases the __init__() method being implicitly called after a new instance of the Home class, home, is created with rooms and stories attributes passed in:
Contribute to Docs
- Learn more about how to get involved.
- Edit this page on GitHub to fix an error or make an improvement.
- Submit feedback to let us know how we can improve Docs.
Learn Python on Codecademy
- Looking for an introduction to the theory behind programming? Master Python while learning data structures, algorithms, and more!
- Includes 6 Courses
- With Professional Certification
- Beginner Friendly.75 hours
- Learn the basics of Python 3.12, one of the most powerful, versatile, and in-demand programming languages today.
- With Certificate
- Beginner Friendly.24 hours