Constructors & Instance Variables

Every time you create an object Python calls a special method called the constructor. In Python this is always named __init__. Inside it you set up the object's own data — called instance variables. The first parameter, self, is the new object being initialised.

Meet self in __init__

class Person:
    def __init__(self, name, age):
        self.name = name  # store data on this object
        self.age  = age

p = Person("Alice", 30)
print(p.name)  # → Alice
print(p.age)   # → 30
Alice
30
  • __init__ is called automatically when you write Person("Alice", 30)
  • self is always the first parameter — Python passes the new object automatically
  • self.name = name means "store name on this Person object"
  • Without self., the value would not be attached to the object

Instance Variables vs Class Variables

class Dog:
    species = "Canis familiaris"  # class variable — one copy, shared

    def __init__(self, name, breed):
        self.name  = name   # instance variable — one per object
        self.breed = breed

d1 = Dog("Rex", "Labrador")
d2 = Dog("Spot", "Dalmatian")
print(d1.name, d2.name)  # → Rex Spot
print(d1.species)         # → Canis familiaris

Multiple Objects, Independent Data

Each object stores its own copy of instance variables. Changing one never affects another.

p1 = Person("Alice", 30)
p2 = Person("Bob", 25)
p1.age = 31          # only p1 is affected
print(p1.age)        # → 31
print(p2.age)        # → 25 (unchanged)

Your Task

  1. Add name and age as parameters to __init__
  2. Inside __init__, assign self.name = name and self.age = age
  3. Run the code — both print statements should work correctly
Section 1/4Meet self in __init__

Meet self in __init__

Explore this concept

Constructors & Instance Variables

Every time you create an object Python calls a special method called the constructor. In Python this is always named __init__. Inside it you set up the object's own data — called instance variables. The first parameter, self, is the new object being initialised.

Meet self in __init__

class Person:
    def __init__(self, name, age):
        self.name = name  # store data on this object
        self.age  = age

p = Person("Alice", 30)
print(p.name)  # → Alice
print(p.age)   # → 30
Alice
30
  • __init__ is called automatically when you write Person("Alice", 30)
  • self is always the first parameter — Python passes the new object automatically
  • self.name = name means "store name on this Person object"
  • Without self., the value would not be attached to the object

Output:

Click "Check" to run your code.