Python · Classes and OOP
Classes and Objects
The full text of this chapter, to read or revisit. To practise, do the exercises.
▶ Do the exercisesExercise 1 — What is a Class?
Until now, you've used Python's built-in types: `str`, `int`, `list`... But what if you want to create your own type? Imagine you want to represent a Codémon — it has a name, a type, a level. You could use a dictionary... but Python lets you create a class instead!
A class is like a blueprint. Just like a Codémon blueprint describes what every Codémon should have (name, type, level), a class describes what your custom objects should look like.
class Codemon:
pass
myCdm = Codemon()
print(type(myCdm))
We just created our first class! `class Codemon:` defines the blueprint. `Codemon()` creates an object (also called an instance) from that blueprint.
OOP meaning
OOP stands for Object-Oriented Programming. It's the programming paradigm we are going to talk about in the few next chapters. It organizes code around objects and their interactions.
Exercise 2 — The __init__ Method
An empty class isn't very useful. We need to give our Codémon some data when we create it. That's what `__init__` does — it's a special method that runs automatically when you create an object.
class Codemon:
def __init__(self):
print("A new Codémon is born!")
myCdm = Codemon()
See? We didn't call `__init__` ourselves — Python calls it automatically when we write `Codemon()`.
Why the double underscores?
`__init__` stands for "initialize". The double underscores `__` around the name tell Python this is a special method — one that Python calls automatically for you.
Exercise 3 — Adding Attributes
Now let's store actual data in our object. We use `self` to attach attributes (variables) to the object. `self` refers to the current object being created.
class Codemon:
def __init__(self, name, element):
self.name = name
self.element = element
myCdm = Codemon("Aquachu", "Water")
print(myCdm.name)
print(myCdm.element)
`self.name = name` stores the value inside the object. Later, we access it with `myCdm.name`. Each object has its own copy of these attributes.
Exercise 4 — Multiple Objects
The whole point of a class is to create multiple objects from the same blueprint. Each object has its own data.
class Codemon:
def __init__(self, name, element):
self.name = name
self.element = element
a = Codemon("Aquachu", "Water")
p = Codemon("Pyrochu", "Fire")
print(a.name, a.element)
print(p.name, p.element)
Same class, but `a` and `p` are different objects with different data. Changing one doesn't affect the other.
Exercise 5 — Creating an Object
What does this code print?
class Codemon:
def __init__(self, name, level):
self.name = name
self.level = level
myCdm = Codemon("Florachu", 25)
print(myCdm.level)
Options
• Florachu
• 25
• Codemon
• Error
Hint : `myCdm.level` accesses the `level` attribute that was set in `__init__`.
Exercise 6 — Create a Class
Complete the class to store a Codémon's name and level.
class Codemon:
def __init__(self, name, level):
____.name = name
self.____ = level
myCdm = Codemon("Zap", 10)
print(myCdm.name, myCdm.level)
Options: self level name myCdm __init__
Hint : `self` refers to the current object. Attributes are set with `self.attribute_name`.
Exercise 7 — Default Values
You can give parameters default values in `__init__`. This way, you don't always have to provide every argument.
class Codemon:
def __init__(self, name, element, level=1):
self.name = name
self.element = element
self.level = level
starter = Codemon("Aquachu", "Water")
veteran = Codemon("Pyrochu", "Fire", 50)
print(f"{starter.name}: Level {starter.level}")
print(f"{veteran.name}: Level {veteran.level}")
`starter` didn't specify a level, so it defaults to 1. `veteran` passed 50, so that's used instead.
Exercise 8 — Default Values
What does this code print?
class Codemon:
def __init__(self, name, hp=100):
self.name = name
self.hp = hp
myCdm = Codemon("Rockachu")
print(myCdm.hp)
Options
• Rockachu
• 100
• Error: missing argument
• None
Hint : When a parameter has a default value, it's used if no argument is provided.
Exercise 9 — Using Default Values
Complete the class so that HP defaults to 100.
class Codemon:
def __init__(self, name, hp=____):
self.name = name
self.hp = hp
myCdm = Codemon("Metachu")
print(myCdm.____)
Options: 100 0 hp name None
Hint : The default value goes after `=` in the parameter. Access it with `myCdm.attribute`.
Exercise 10 — Modifying Attributes
Once an object is created, you can modify its attributes directly. Just assign a new value with `=`.
class Codemon:
def __init__(self, name, level=1):
self.name = name
self.level = level
myCdm = Codemon("Aquachu")
print(f"{myCdm.name}: Level {myCdm.level}")
myCdm.level = 15
print(f"{myCdm.name}: Level {myCdm.level}")
You can also add new attributes after creation: `myCdm.nickname = "Aqua"`. But it's better practice to define all attributes in `__init__`.
Exercise 11 — Modify an Attribute
Complete the code to level up the Codémon by 1.
class Codemon:
def __init__(self, name, level=1):
self.name = name
self.level = level
myCdm = Codemon("Pyrochu", 10)
myCdm.____ = myCdm.level + ____
print(f"{myCdm.name}: Level {myCdm.level}")
Options: level name 1 5 10
Hint : To level up by 1, set the `level` attribute to its current value plus `1`.
Exercise 12 — Independent Objects
What does this code print?
class Codemon:
def __init__(self, name, level=1):
self.name = name
self.level = level
a = Codemon("Aquachu", 10)
b = Codemon("Aquachu", 10)
a.level = 50
print(b.level)
Options
• 50
• 10
• 1
• Error
Hint : Each object is ***independent***. Changing one doesn't change the other, even if they have the same name.
Exercise 13 — OOP Vocabulary
Match each term with its definition.
Items to match
• Class
• Object
• `__init__`
• `self`
• Attribute
Definitions
• A blueprint for creating objects
• An instance created from a class
• Method called when creating an object
• Refers to the current object
• A variable stored inside an object
Exercise 14 — Create a Codémon Class
Create a `Codemon` class with:
1. `__init__` that takes `name`, `element`, `level` (default 1), and `hp` (default 100)
2. Create 3 different Codémon
3. Level up the first one by 5
4. Print all 3 like: `"Aquachu (Water) - Lv.6 - HP: 100"`
Starter code
# Create the Codemon class
# Create 3 Codémon
# Level up the first one by 5
# Print all 3
Back to the course