__init__ Method

Object initialization

Interview Relevant: Constructor in Python

__init__ Method

Initialize new objects (constructor).

Code Examples

The __init__ constructor method.

python
1class Person:
2    def __init__(self, name, age=0):
3        self.name = name
4        self.age = age
5        self.friends = []  # Default mutable
6
7# Required and optional args
8p1 = Person("Alice", 25)
9p2 = Person("Bob")  # age defaults to 0
10
11# __init__ vs __new__
12# __new__ creates the instance
13# __init__ initializes it
14
15class Singleton:
16    _instance = None
17
18    def __new__(cls):
19        if cls._instance is None:
20            cls._instance = super().__new__(cls)
21        return cls._instance

AI Tutor

Ask about the topic

Sign in Required

Please sign in to use the AI tutor

Sign In