Skip to content
Codewilds

Lesson 24 of 34 · Classes & OOP

Python Classes and Objects: __init__, Methods and Attributes

medium20 XP3 min read

So far your data has lived in separate variables, lists and dictionaries, with functions operating on them from the outside. Object-oriented programming bundles data and the behaviour that belongs to it into one unit. In Python you do that with a class — a blueprint from which you create as many objects (instances) as you need.

Every value you've used is already an object: "hiss".upper() calls the upper method of a str object. Now you'll design your own types.

Defining a class

class Potion:
    def __init__(self, name, power):
        self.name = name
        self.power = power


healing = Potion("Healing", 25)
mana = Potion("Mana", 40)
print(healing.name, healing.power)   # Healing 25
print(mana.power)                    # 40
  • class Potion: starts the definition. Class names use CamelCase by convention.
  • __init__ is the initializer. Python calls it automatically when you create an object with Potion("Healing", 25), passing your arguments along.
  • self.name = name creates an instance attribute: a variable that belongs to this particular object. Each potion has its own name and power.

What is self?

self is the object the method is working on. You never pass it yourself — Python supplies it. When you call healing.describe(), Python runs Potion.describe(healing) behind the scenes, so inside the method self is healing. The name self is a convention, but one every Python developer follows.

Methods

Functions defined inside a class are methods. They can read and change the object's attributes through self, and call each other with self.method():

class Lantern:
    def __init__(self, oil):
        self.oil = oil

    def is_lit(self):
        return self.oil > 0

    def burn(self, hours):
        self.oil = max(self.oil - hours, 0)
        return self.is_lit()


lantern = Lantern(3)
print(lantern.burn(2))   # True  (1 hour of oil left)
print(lantern.burn(2))   # False (oil can't drop below 0)
print(lantern.oil)       # 0

Methods that change an object's attributes are how objects keep their data consistent — here, the oil never goes negative.

Class attributes

A variable defined directly in the class body is a class attribute, shared by every instance. It's a good home for constants and settings that apply to all objects:

class Lantern:
    MAX_OIL = 10          # class attribute

    def __init__(self, oil):
        self.oil = min(oil, Lantern.MAX_OIL)   # instance attribute


print(Lantern.MAX_OIL)      # 10
print(Lantern(50).oil)      # 10

You can read it through the class (Lantern.MAX_OIL) or through any instance (self.MAX_OIL). But assigning through an instance — self.MAX_OIL = 5 — creates a new instance attribute that hides the shared one for that object only.

Objects are independent — and checkable

Each instance has its own attributes, so changing one object doesn't affect another. Use isinstance() to check what kind of object you have:

a = Lantern(3)
b = Lantern(8)
a.burn(3)
print(a.oil, b.oil)               # 0 8
print(isinstance(a, Lantern))     # True

Common mistakes

  • Forgetting self in a method definition: def burn(hours): raises TypeError: Lantern.burn() takes 1 positional argument but 2 were given when called.
  • Forgetting the self. prefix: oil = oil - hours inside a method just creates a local variable; the object's attribute doesn't change.
  • Mutable class attributes: items = [] in the class body is one list shared by every instance. Create per-object lists in __init__ with self.items = [].
  • Forgetting the parentheses: lantern.is_lit is the method itself; lantern.is_lit() calls it.

Assignment

Write a Hero class:

  • A class attribute MAX_LEVEL = 10.
  • __init__(self, name, max_health=100) stores name and max_health, sets health to max_health and level to 1.
  • take_damage(amount) lowers health by amount, but never below 0, and returns the new health.
  • heal(amount) raises health by amount, but never above max_health, and returns the new health.
  • is_alive() returns True while health is above 0.
  • level_up() increases level by 1, but never beyond Hero.MAX_LEVEL, and returns the new level.
ada = Hero("Ada")
ada.take_damage(30)   # 70
ada.heal(50)          # 100 (capped at max_health)
ada.is_alive()        # True
ada.level_up()        # 2

Premium lesson

Unlock the full Learn Python course

  • All 34 lessons, bosses and quizzes — lifetime access
  • One payment of $35, no subscription
  • Finish within 30 days and claim $10.50 (30%) back
Play the 8 free lessons

Want more than one course?

The All-Access Pass unlocks all 8 courses and every new one we release, for $120 once.

Classes, objects and structs in other languages

Need a quick reminder? The Python cheat sheet has every topic of Learn Python on one page.

Lesson last updated on .

Write code ↓
Python+20 XP

Lesson 24 is part of the full course. The first 8 lessons are free.

Premium lesson

Unlock the full Learn Python course

  • All 34 lessons, bosses and quizzes — lifetime access
  • One payment of $35, no subscription
  • Finish within 30 days and claim $10.50 (30%) back
Play the 8 free lessons

Want more than one course?

The All-Access Pass unlocks all 8 courses and every new one we release, for $120 once.