Classes and Objects
You’ve already been using objects this whole time. Strings, lists, and even the img and draw variables from Pillow are all objects. Now you’ll learn what that means — and how to build your own.
What is an Object?
An object is a variable that bundles together data (attributes) and behavior (methods).
For example, a list object stores items (data) and has methods like .append() and .pop() (behavior).
What is a Class?
A class is a blueprint for creating objects. It defines what attributes and methods every object of that type will have.
Here’s a simple class that represents a dog:
class Dog:
def __init__(self, name, age):
self.name = name
self.age = ageDog is the blueprint. self.name and self.age are the attributes — every dog will have its own name and age.
Creating an Object
To create an object from a class, call the class like a function:
dog1 = Dog("Buddy", 3)
dog2 = Dog("Max", 5)Each object is called an instance of the class. dog1 and dog2 are two separate instances — they share the same blueprint but have different names and ages.
Accessing Attributes
Use dot notation to access an object’s attributes:
print(dog1.name) # Buddy
print(dog2.age) # 5You’ve used dot notation before — my_list.append(), "hello".upper(). Those are method calls on list and string objects.
Class Variables
Some attributes are the same for every instance. You can define these directly on the class — outside of __init__ — and they’ll be shared across all objects:
class Dog:
species = "Canis familiaris"
def __init__(self, name, age):
self.name = name
self.age = age
dog1 = Dog("Buddy", 3)
dog2 = Dog("Max", 5)
print(dog1.species) # Canis familiaris
print(dog2.species) # Canis familiarisspecies is a class variable — every dog shares it. name and age are instance variables — each dog has its own.