OOP – __init__ Method, online
Six activities your students do on their own devices. See who's finished, and their scores.
Learning
Understanding
Testing
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
What students will learn in this module
Every question in Module 50
Quick questions
- What does __init__ do?ADeletes the objectBInitializes a new object automatically
- When does __init__ run?AWhen an object is createdBWhen an object is deleted
- What must be the first parameter of __init__?AselfBthis
- class Dog:\n def __init__(self, name):\n self.name = name\nDog('Rex') what is self.name?A'Rex'B'name'
- Do you pass 'self' when creating an object?AYesBNo Python passes it automatically
Key terms
Students type the meaning of:
__init__selfself.attributeConstructor
Match the pairs
class Dog:
def __init__(name):
self.name = nameMatch it to what it doesclass Dog:
def __init__(self, name):
self.name = name
Dog()Match it to what it doesclass Dog:
def __init__(self, name):
self.name = nameMatch it to what it doesd = Dog('Rex')
print(d.name)Match it to what it doesclass Dog:
def __init__(self,n):
self.name=n
d=Dog('Rex')
print(d.name)Match it to what it doesclass Point:
def __init__(self,x,y):
self.x=x
self.y=y
p=Point(3,4)
print(p.x)Match it to what it doesFill in the blanks
class Dog: def ________(self, name): self.name = nameclass Dog: def ________(self): self.name = nameclass Dog: def ________(self, name): ____.name = namedog = Dog(_____) print(dog.name)
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)
