OOP – __init__ Method, online

Six activities your students do on their own devices. See who's finished, and their scores.

OOP – __init__ Method in one minute

What students need to know

__init__ runs automatically when Dog('Rex') is called. self.name stores the value. Once set in __init__, the attribute is accessible on the object as d.name.

Dog('Rex') creates the object and immediately calls __init__ with 'Rex'. Python uses self (not this) — it's the reference to the object being created.

Mistakes students make

  • Missing self as the first parameter.
  • Need DOUBLE underscores: __init__ not _init_.
  • Must use self.name to save on the object. name alone is just a local variable.
  • __init__ expects a name argument Dog() without it causes TypeError.
PREVIOUS · MODULE 49OOP – Classes & Objects
YOU ARE HERE · MODULE 50OOP – __init__ Method
NEXT · MODULE 51OOP – Methods

Discover other journeys with this module

What students will learn in this module

Every question in Module 50

Quick questions

  1. What does __init__ do?ADeletes the objectBInitializes a new object automatically
  2. When does __init__ run?AWhen an object is createdBWhen an object is deleted
  3. What must be the first parameter of __init__?AselfBthis
  4. class Dog:\n def __init__(self, name):\n self.name = name\nDog('Rex') what is self.name?A'Rex'B'name'
  5. Do you pass 'self' when creating an object?AYesBNo Python passes it automatically

Key terms

Students type the meaning of:

  • __init__
  • self
  • self.attribute
  • Constructor

Match the pairs

class Dog:
    def __init__(name):
        self.name = name
Match it to what it does
class Dog:
    def __init__(self, name):
        self.name = name
Dog()
Match it to what it does
class Dog:
    def __init__(self, name):
        self.name = name
Match it to what it does
d = Dog('Rex')
print(d.name)
Match it to what it does
class Dog:
    def __init__(self,n):
        self.name=n
d=Dog('Rex')
print(d.name)
Match it to what it does
class Point:
    def __init__(self,x,y):
        self.x=x
        self.y=y
p=Point(3,4)
print(p.x)
Match it to what it does

Fill in the blanks

  1. class Dog:
        def ________(self, name):
            self.name = name
  2. class Dog:
        def ________(self):
            self.name = name
  3. class Dog:
        def ________(self, name):
            ____.name = name
  4. dog = Dog(_____)
    print(dog.name)
  5. class Person:
        def __init__(self, name, age):
            self.___ = age

Spot the error

Question 1

Aclass Dog:B    def __init__(name):C        self.name = name

Question 2

Aclass Dog:B    def _init_(self, name):C        self.name = name

Question 3

Aclass Dog:B    def __init__(self, name):C        name = name

Question 4

Aclass Dog:B    def __init__(self, name):C        self.name = nameDEdog = Dog()Fprint(dog.name)

Question 5

Aclass Dog:B    def __init__(self, name):C        self.name = nameDEdog = Dog('Rex', self)