🏗️ Classes & Objects, lesson 1 of 6
Classes and objects
Create your own types that bundle data together.
9 min
1 exercise
2 quizzes
0/3 solved
Getting Python ready… examples can run in a moment.
You've used built-in types like str, list and
dict. A class lets you define your own type.
Think of it as a blueprint: each object (also
called an instance) built from it carries its own
data.
class Dog:
def __init__(self, name, age):
self.name = name
self.age = age
__init__runs automatically when you create an object. It sets up the object's attributes.selfis the object being built;self.name = namestores the value on it.
Your first class
Each object keeps its own name and age. Create a third dog and print its name.
What does this print?
Attributes are variables attached to an object.
Read them with a dot (rex.age) and change them by
assigning (rex.age += 1). __init__ can take
default values like any function.
By convention class names use CapWords, while
functions and attributes use snake_case.
Defaults and changing attributes
Each player gets a fresh empty inventory list,
because it's created inside __init__. Give the boss
a "club" too.
Forgetting self
Change the line to self.name = name and run it again.
Inside a class, what does self refer to?
A Book class
- Finish
Book.__init__so it storestitle,authorandpagesas attributes, plus areadattribute that starts asFalse. - Create
my_bookfor Dune by Frank Herbert, 412 pages.