KAHIBARO Bookshelves
Discord Login Register

13.3. The `__init__` method

What `__init__` Does in a Class

In Python, __init__ is a special method that runs automatically every time you create a new object from a class.

You’ll usually use it to:

  • Receive values (arguments) when creating an object
  • Store those values in attributes on the object
  • Set up any default values the object should start with

__init__ is not the only method a class can have, but it is the one that controls how a new object is initialized.

Basic pattern:

class ClassName:
    def __init__(self, parameters_here):
        # set up the new object
        # create attributes
        pass

A First Example of `__init__`

Here’s a simple class with an __init__ method:

class Person:
    def __init__(self, name, age):
        # create attributes on this new object
        self.name = name
        self.age = age
# creating objects
p1 = Person("Alice", 30)
p2 = Person("Bob", 25)
print(p1.name)  # Alice
print(p2.age)   # 25

Key ideas:

  • __init__ runs when you call Person("Alice", 30)
  • The arguments "Alice" and 30 are passed into __init__(self, name, age)
  • Inside __init__, these values are stored on the object as self.name and self.age
  • After initialization, you can access those attributes on each object

Why `self` Is the First Parameter

You’ll always see self as the first parameter of __init__ (and other methods).

Inside a class method:

  • self refers to the specific object being created or used
  • When you create an object with p1 = Person("Alice", 30), Python secretly does something like:
    1. Create an empty Person object
    2. Call Person.__init__(p1, "Alice", 30)

So inside __init__, self is p1 for the first object and p2 for the second, and so on.

You do not pass self yourself:

# Correct
p1 = Person("Alice", 30)
# Incorrect – do NOT pass self
# p1 = Person(self, "Alice", 30)

Storing Values in Attributes

The main job of __init__ is to set up attributes on the new object, usually using self.attribute_name = value.

class Rectangle:
    def __init__(self, width, height):
        self.width = width      # attribute
        self.height = height    # attribute
r = Rectangle(5, 10)
print(r.width)   # 5
print(r.height)  # 10

Here:

  • width and height are parameters to __init__
  • self.width and self.height are attributes on the object
  • You can give them the same names, but they are not the same thing:
    • Left side: self.width → belongs to the object
    • Right side: width → parameter value passed in

Using Default Values in `__init__`

You can give parameters in __init__ default values, so they become optional when creating an object.

class Person:
    def __init__(self, name, age=18, country="Unknown"):
        self.name = name
        self.age = age
        self.country = country
p1 = Person("Alice")                          # uses default age and country
p2 = Person("Bob", 25)                        # sets age, default country
p3 = Person("Charlie", 40, "Australia")       # sets all three
print(p1.age, p1.country)   # 18 Unknown
print(p2.age, p2.country)   # 25 Unknown
print(p3.age, p3.country)   # 40 Australia

This lets you create flexible objects while still keeping sensible defaults.

Using Keyword Arguments with `__init__`

When you have multiple parameters, using keyword arguments when creating objects makes the code clearer:

class Car:
    def __init__(self, brand, model, year, electric=False):
        self.brand = brand
        self.model = model
        self.year = year
        self.electric = electric
car1 = Car("Toyota", "Corolla", 2020)
car2 = Car(brand="Tesla", model="Model 3", year=2022, electric=True)
print(car1.electric)  # False
print(car2.electric)  # True

Here, Car(...) and Car(brand="Tesla", ...) both call __init__, but using keywords makes the meaning of each argument obvious.

Objects Without Custom `__init__`

You don’t have to define __init__ in every class. If you skip it, Python uses a default one that doesn’t take any extra arguments.

class Empty:
    pass
e = Empty()       # works
# e = Empty(10)   # error: takes no arguments

If your class doesn’t need any initial data, you can leave out __init__, but in practice most useful classes will define one.

Adding Logic Inside `__init__`

__init__ can do more than just store values. It can:

  • Calculate values
  • Validate arguments
  • Transform input before storing
class BankAccount:
    def __init__(self, owner, balance):
        if balance < 0:
            raise ValueError("Balance cannot be negative")
        self.owner = owner
        self.balance = balance
account = BankAccount("Alice", 100)
print(account.balance)  # 100
# account2 = BankAccount("Bob", -50)  # would raise ValueError

You can also compute derived attributes:

class Circle:
    def __init__(self, radius):
        self.radius = radius
        self.diameter = radius * 2   # computed attribute
c = Circle(5)
print(c.radius)   # 5
print(c.diameter) # 10

Common Mistakes with `__init__`

Here are typical beginner errors and how to fix them.

1. Forgetting `self` in the parameter list

class Person:
    # Wrong: missing self
    def __init__(name, age):
        self.name = name  # error: self is not defined
        self.age = age
# Correct version:
class Person:
    def __init__(self, name, age):
        self.name = name
        self.age = age

2. Forgetting to use `self.` when creating attributes

class Person:
    def __init__(self, name, age):
        name = name      # Wrong: does not create an attribute
        age = age        # Just reassigns the local variables
# Correct:
class Person:
    def __init__(self, name, age):
        self.name = name
        self.age = age

Without self., the values are lost after __init__ finishes.

3. Passing the wrong number of arguments

If __init__ expects some parameters, you must supply them (unless they have default values).

class Point:
    def __init__(self, x, y):
        self.x = x
        self.y = y
# Wrong:
# p = Point(5)         # missing y
# p = Point()          # missing x and y
# Correct:
p = Point(5, 10)

If you want flexibility, use defaults:

class Point:
    def __init__(self, x=0, y=0):
        self.x = x
        self.y = y
p1 = Point()        # (0, 0)
p2 = Point(5)       # (5, 0)
p3 = Point(1, 2)    # (1, 2)

Example: A Simple Class Using `__init__`

Here’s a slightly more complete example that uses __init__ along with another method:

class Student:
    def __init__(self, name, grades=None):
        self.name = name
        # Use an empty list if no grades are provided
        if grades is None:
            self.grades = []
        else:
            self.grades = grades
    def average_grade(self):
        if not self.grades:
            return 0
        return sum(self.grades) / len(self.grades)
s1 = Student("Alice", [90, 80, 85])
s2 = Student("Bob")
print(s1.name, s1.average_grade())  # Alice 85.0
print(s2.name, s2.average_grade())  # Bob 0

Here, __init__:

  • Accepts optional grades
  • Ensures every Student object has a grades attribute
  • Provides a safe default (an empty list) when grades are not given

When to Use `__init__`

Use __init__ whenever you need to:

  • Make sure every new object has certain attributes
  • Require some information at creation time (like name, age, width, height)
  • Set useful default values
  • Validate incoming data or compute initial values

In most real-world classes, defining a clear and simple __init__ is one of the first steps in designing the class.

Views: 0

Comments

Please login to add a comment.

Don't have an account? Register now!

Where to Move

Move chapter:

  • ☰ 1. Chapter 1: What Is Programming?
    • ☰ 1.1. What is a computer program?
      • ☰ 1.2. What is Python?
        • ☰ 1.3. Where is Python used?
          • ☰ 1.4. How programming helps solve problems
            • ☰ 1.5. Your first Python program
            • ☰ 2. Chapter 2: Setting Up Python
              • ☰ 2.1. Installing Python (Windows / macOS / Linux)
                • ☰ 2.2. Using Python in the terminal
                  • ☰ 2.3. Using an IDE (IDLE / VS Code)
                    • ☰ 2.4. Running Python scripts
                      • ☰ 2.5. Python interactive mode
                      • ☰ 3. Chapter 3: Variables and Data Types
                        • ☰ 3.1. What is a variable?
                          • ☰ 3.2. Creating variables
                            • ☰ 3.3. Numbers
                              • ☰ 3.4. Test
                                • ☰ 3.5. Boolean values
                                  • ☰ 3.6. Type checking
                                  • ☰ 4. Chapter 4: Basic Operations
                                    • ☰ 4.1. Arithmetic operations
                                      • ☰ 4.2. Working with numbers
                                        • ☰ 4.3. String operations
                                          • ☰ 4.4. Combining text and variables
                                            • ☰ 4.5. Comments in Python
                                            • ☰ 5. Chapter 5: User Input and Output
                                              • ☰ 5.1. Getting input from the user
                                                • ☰ 5.2. Converting input to numbers
                                                  • ☰ 5.3. Formatting output
                                                    • ☰ 5.4. Writing interactive programs
                                                    • ☰ 6. Chapter 6: Conditions
                                                      • ☰ 6.1. Comparison operators
                                                        • ☰ 6.2. Logical operators
                                                          • ☰ 6.3. if, elif, else
                                                            • ☰ 6.4. Nested conditions
                                                              • ☰ 6.5. Common beginner mistakes
                                                              • ☰ 7. Chapter 7: Loops
                                                                • ☰ 7.1. Why loops are useful
                                                                  • ☰ 7.2. for loops
                                                                    • ☰ 7.3. while loops
                                                                      • ☰ 7.4. Loop counters
                                                                        • ☰ 7.5. break and continue
                                                                          • ☰ 7.6. Loop exercises
                                                                          • ☰ 8. Chapter 8: Data Collections
                                                                            • ☰ 8.1. Lists
                                                                              • ☰ 8.2. Tuples
                                                                                • ☰ 8.3. Dictionaries
                                                                                  • ☰ 8.4. Sets (basics)
                                                                                    • ☰ 8.5. Choosing the right data structure
                                                                                    • ☰ 9. Chapter 9: Functions
                                                                                      • ☰ 9.1. Why functions matter
                                                                                        • ☰ 9.2. Defining functions
                                                                                          • ☰ 9.3. Parameters and arguments
                                                                                            • ☰ 9.4. Return values
                                                                                              • ☰ 9.5. Scope (local vs global)
                                                                                                • ☰ 9.6. Reusing code
                                                                                                • ☰ 10. Chapter 10: Working with Files
                                                                                                  • ☰ 10.1. What is a file?
                                                                                                    • ☰ 10.2. Reading text files
                                                                                                      • ☰ 10.3. Writing and appending files
                                                                                                        • ☰ 10.4. File paths
                                                                                                          • ☰ 10.5. Simple file-based programs
                                                                                                          • ☰ 11. Chapter 11: Errors and Debugging
                                                                                                            • ☰ 11.1. Types of errors
                                                                                                              • ☰ 11.2. Reading error messages
                                                                                                                • ☰ 11.3. Common beginner errors
                                                                                                                  • ☰ 11.4. try and except
                                                                                                                    • ☰ 11.5. Debugging strategies
                                                                                                                    • ☰ 12. Chapter 12: Using Python Libraries
                                                                                                                      • ☰ 12.1. What is a library?
                                                                                                                        • ☰ 12.2. Importing modules
                                                                                                                          • ☰ 12.3. Standard libraries
                                                                                                                            • ☰ 12.3.1. math
                                                                                                                              • ☰ 12.3.2. random
                                                                                                                                • ☰ 12.3.3. datetime
                                                                                                                                • ☰ 12.4. Installing external libraries with pip
                                                                                                                                • ☰ 13. Chapter 13: Object-Oriented Programming
                                                                                                                                  • ☰ 13.1. What is object-oriented programming?
                                                                                                                                    • ☰ 13.2. Classes and objects
                                                                                                                                      • ☰ 13.3. The `__init__` method
                                                                                                                                        • ☰ 13.4. Attributes and methods
                                                                                                                                          • ☰ 13.5. Encapsulation
                                                                                                                                            • ☰ 13.6. Inheritance (basics)
                                                                                                                                              • ☰ 13.7. Simple OOP examples
                                                                                                                                              • ☰ 14. Chapter 14: Automation with Python
                                                                                                                                                • ☰ 14.1. What is automation?
                                                                                                                                                  • ☰ 14.2. Automating simple tasks
                                                                                                                                                    • ☰ 14.3. Working with files and folders
                                                                                                                                                      • ☰ 14.4. Automating text processing
                                                                                                                                                        • ☰ 14.5. Scheduling scripts
                                                                                                                                                          • ☰ 14.6. Practical automation examples
                                                                                                                                                          • ☰ 15. Chapter 15: Web Development with Python
                                                                                                                                                            • ☰ 15.1. How the web works (basic overview)
                                                                                                                                                              • ☰ 15.2. Introduction to Flask
                                                                                                                                                                • ☰ 15.3. Creating a simple web server
                                                                                                                                                                  • ☰ 15.4. Routing and templates
                                                                                                                                                                    • ☰ 15.5. Handling user input (forms)
                                                                                                                                                                      • ☰ 15.6. Very basic APIs
                                                                                                                                                                      • ☰ 16. Chapter 16: Data Science with Python
                                                                                                                                                                        • ☰ 16.1. What is data science?
                                                                                                                                                                          • ☰ 16.2. Working with data
                                                                                                                                                                            • ☰ 16.3. Introduction to NumPy
                                                                                                                                                                              • ☰ 16.4. Introduction to pandas
                                                                                                                                                                                • ☰ 16.5. Data visualization with matplotlib
                                                                                                                                                                                  • ☰ 16.6. Simple data analysis examples
                                                                                                                                                                                  • ☰ 17. Chapter 17: Mini Projects
                                                                                                                                                                                    • ☰ 17.1. Number guessing game
                                                                                                                                                                                      • ☰ 17.2. Simple calculator
                                                                                                                                                                                        • ☰ 17.3. To-do list
                                                                                                                                                                                          • ☰ 17.4. Password generator
                                                                                                                                                                                            • ☰ 17.5. Quiz application
                                                                                                                                                                                              • ☰ 17.6. Small web or data project
                                                                                                                                                                                              • ☰ 18. Chapter 18: Next Steps
                                                                                                                                                                                                • ☰ 18.1. How to practice Python
                                                                                                                                                                                                  • ☰ 18.2. Writing clean and readable code
                                                                                                                                                                                                    • ☰ 18.3. Choosing a specialization
                                                                                                                                                                                                      • ☰ 18.3.1. Web development
                                                                                                                                                                                                        • ☰ 18.3.2. Data science
                                                                                                                                                                                                          • ☰ 18.3.3. Automation
                                                                                                                                                                                                            • ☰ 18.3.4. Software development
                                                                                                                                                                                                            • ☰ 18.4. Learning resources and communities
                                                                                                                                                                                                            • ☰ 19. Appendix
                                                                                                                                                                                                              • ☰ 19.1. Python syntax cheat sheet
                                                                                                                                                                                                                • ☰ 19.2. Common errors and solutions
                                                                                                                                                                                                                  • ☰ 19.3. Glossary of terms