8.2 Classes and Objects
We learn how to define classes with the __init__ method and how to create objects (instances) from them.
A class is defined with the `class` keyword, followed by the class name (by convention, it starts with a capital letter, e.g., `MyClass`). Inside the class, we define its methods, which are functions that belong to the class.
The __init__ Method and self
The special method `__init__` (also called the "constructor" or "initializer") is automatically called every time a new object is created from the class. Its main purpose is to initialize the new object's attributes. The first argument of every method in a class is, by convention, `self`. This `self` is a reference to the object itself being created. Through `self`, we can store data that will be unique to each object (instance attributes), e.g., `self.name = name`.
# Class with __init__ and attributes
class Car:
def __init__(self, brand, model, color, year):
self.brand = brand
self.model = model
self.color = color
self.year = year
self.speed = 0
car1 = Car("Toyota", "Corolla", "Blue", 2020)
print(f"car1 is a {car1.color} {car1.brand} {car1.model} from {car1.year}.")
Class vs. Instance Attributes
Attributes defined inside `__init__` with `self` (e.g., `self.name`) are called **instance attributes** and are unique to each object. Conversely, attributes defined directly within the class, but outside any method, are called **class attributes** and are common and accessible by all objects of the class.
# Class and Instance Attributes
class Pet:
species = "Mammal" # Class attribute
def __init__(self, name):
self.name = name # Instance attribute
pet1 = Pet("Lucky")
pet2 = Pet("Mitsy")
print(f"{pet1.name} is a {pet1.species}.") # 'species' is common
print(f"{pet2.name} is a {pet2.species}.")
Explore More with AI
Use AI to generate new examples, delve deeper into theory, or get your questions answered.