Classes and Objects
A class is a blueprint.
An object is one thing built from that blueprint.
Think of CookieCutter as the class. Each cookie is an object.
The class holds the shape. Each object holds its own frosting and name.
Defining a class
Use class, then a name with a capital letter.
Usually you write __init__ to set starting values.
Methods are functions that live on the class.
What self means
self is the object you are working on.
When you call buddy.bark(), Python passes buddy in as self.
Inside methods, use self.something to reach that object's data.
Instance attributes
Each object can keep its own drawers.
Buddy has name Buddy. Luna has name Luna.
Same class. Different data.
Methods that return values
Methods can compute and return answers.
Just like normal functions, but they can use self.
Readable print with __str__
Define __str__ so print shows something friendly.
Without it, print may show a cryptic object address.
Many objects from one class
Class = blueprint
Object = one built thing
Attributes = data on the object
Methods = actions the object can do
Tip: Class is the blueprint. Object is one instance. Methods take self first.
Test yourself
Three quick questions made just for this lesson. Earn 10 XP per correct answer.