Introduction

In the previous lesson, you learned how to create a class and make objects from it. However, all objects created from the class shared the same data. In real programs, this is rarely what we want.

In this lesson, you will learn how to:

  • Use the constructor method (__init__) to set up objects properly.
  • Use self so each object keeps track of its own data.
  • Pass data into a class when creating objects.

This is a huge step forward in understanding Object Oriented Programming, because it allows every object created from a class to be unique.

What is a Constructor?

A constructor is a special method that runs automatically when a new object is created from a class.

In Python, the constructor is always called:

__init__

It is used to:

  • Create attributes
  • Store data inside the object
  • Set starting values

What is self?

The keyword self refers to the current object.

It allows:

  • Each object to store its own values
  • Python to know which object’s data is being accessed

You can think of self as meaning:

“this specific object”

Example: A Student Class with a Constructor

Example: A Student Class with a Constructor

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

student1 = Student("Alex")
student2 = Student("Jamie")

print(student1.name)
print(student2.name)

Here’s what’s happening:

  • __init__ runs when a new object is created
  • self.name stores data inside the object
  • Each student object has its own name

Predict:

Look at the following code. What do you think will be printed?

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

student1 = Student("Alex")
student2 = Student("Jamie")

print(student1.name)
print(student2.name)

Questions to think about:

  • Will both students have the same name?
  • Why or why not?

Run:

Run the code below and check your prediction.

Investigate:

Now let’s explore how objects store their own data.

Try this:

  • Add a second attribute called age
  • Give each student a different age

Your code should look similar to this:

Think about:

  • Why do the objects not overwrite each other’s data?
  • What role does self play?

Modify:

The following program attempts to use a constructor, but it does not work correctly.

Use the editor below to modify the code so that the student’s name is stored properly and can be printed.

The problem

  • The attribute is not attached to the object
  • self is missing

Your task

Modify the code so that:

  • The name is stored inside the object
  • student.name prints correctly

Hint:

To attach data to an object, you must use:

self.attribute_name = value
Scroll to Top