CodingNic

Object-Oriented Programming

The __init__ Constructor

Object-Oriented Programming 30 min read

The __init__ Constructor

The init Constructor

So far, you created objects first, then added attributes later.

python
tom = Student()
tom.name = "Tom"
tom.score = 85

There is a better way.

Python gives us __init__() to set up objects when they are created.

What Is init()?

__init__() is a special method called automatically when you create an object.

It is used to give starting values to attributes.

Why It Matters

It helps you:

  • create objects faster
  • avoid missing attributes
  • keep code cleaner
  • give every object a clear starting state

Basic Structure

python
class ClassName:
    def __init__(self, value):
        self.attribute = value

First Example

python
class Student:
    def __init__(self, name):
        self.name = name

tom = Student("Tom")
print(tom.name)

Output

text
Tom

Two Attributes

python
class Student:
    def __init__(self, name, score):
        self.name = name
        self.score = score

sara = Student("Sara", 92)

print(sara.name)
print(sara.score)

Output

text
Sara
92

How It Works

When you run:

python
sara = Student("Sara", 92)

Python automatically runs:

python
__init__(self, "Sara", 92)

and saves the values.

Add Other Methods Too

python
class Student:
    def __init__(self, name, score):
        self.name = name
        self.score = score

    def show_info(self):
        print(self.name, self.score)

tom = Student("Tom", 85)
tom.show_info()

Output

text
Tom 85

Multiple Objects

python
tom = Student("Tom", 85)
sara = Student("Sara", 92)

print(tom.name)
print(sara.name)

Output

text
Tom
Sara

Common Beginner Errors

Forgetting self

python
def __init__(name):

Wrong.

Use:

python
def __init__(self, name):

Wrong Number of Values

If __init__() expects two values, give two values.

Code Along

Create a class called Book.

Use __init__() with:

  • title
  • price

Create one book and print both values.

Mini Challenge

Create a class called Phone.

Steps:

  • Use __init__() with:

    • brand
    • model
    • price
  • Create:

python
phone1 = Phone("Apple", "iPhone", 999)
  • Print all values

Expected output:

text
Apple
iPhone
999

Real World Use Case

Apps use constructors to create users, products, orders, bank accounts, and game characters with starting data.

Quiz

  1. What is __init__()?
  2. When does it run?
  3. Why is it useful?
  4. Can a class have other methods too?

Assignment

Create a class called Car with brand and color using __init__().

Summary

You learned how __init__() gives objects starting values when they are created.