__init__
- Python course
- Intermediate
- Lesson 4/116
- 4 min
Learn the constructor with __init__.
The __init__ method
__init__ is a special method called automatically when an instance is created. It is used to set up instance attributes; hence it is called the constructor.
Example: class User:\n def __init__(self, name):\n self.name = name. When you write u = User("Alex"), __init__ runs and u.name becomes "Alex". The name starts and ends with two underscores; this marks special methods.
Assigning attributes with self
Inside __init__ you assign the parameter to an instance attribute with self.name = name. self points to the instance being created.
Example: def __init__(self, name, age):\n self.name = name\n self.age = age. Then u = User("Alex", 30) makes both u.name and u.age ready. The parameter and attribute names do not have to match, but it is a common choice.
Practice Add __init__ to the User class
Define a class named User. Add the method def __init__(self, name): and in the body write self.name = name. After the class, create an instance with u = User("Alex") and print u.name.
Starter code
# Define the User class and the __init__ methodSample solution
# Define the User class and the __init__ method
class User:
def __init__(self, name):
self.name = name
u = User("Alex")
print(u.name)Expected output
Alex
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 When does __init__ run?
- When the class is defined
- Automatically when the script starts
- When a method is called
- When an instance is created with User("Alex") Correct answer
Explanation: __init__ is called automatically when an instance is created.
2 Complete the __init__ signature
class User:
def __init__(self, ____):
self.name = name
class User:
def __init__(self, name):
self.name = name
Explanation: The name parameter is taken from outside and assigned to self.name.
3 Match the __init__ concepts
| Term | Meaning |
|---|---|
__init__ |
Constructor |
self.name |
Instance attribute |
User("Alex") |
Instantiation |