Lesson 24 of 34 · Classes & OOP
Python Classes and Objects: __init__, Methods and Attributes
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 withPotion("Healing", 25), passing your arguments along.self.name = namecreates an instance attribute: a variable that belongs to this particular object. Each potion has its ownnameandpower.
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
selfin a method definition:def burn(hours):raisesTypeError: Lantern.burn() takes 1 positional argument but 2 were givenwhen called. - Forgetting the
self.prefix:oil = oil - hoursinside 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__withself.items = []. - Forgetting the parentheses:
lantern.is_litis 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)storesnameandmax_health, setshealthtomax_healthandlevelto1.take_damage(amount)lowershealthbyamount, but never below0, and returns the new health.heal(amount)raiseshealthbyamount, but never abovemax_health, and returns the new health.is_alive()returnsTruewhilehealthis above0.level_up()increaseslevelby 1, but never beyondHero.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() # 2Premium 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
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
- JavaScript Classes: Constructors, Getters and Setters · JavaScript
- Go Structs: Define Your Own Types · Go
- Java Classes and Objects: Constructors and new · Java
- C# Classes and Objects · C#
Need a quick reminder? The Python cheat sheet has every topic of Learn Python on one page.
Lesson last updated on .