Sub topic 1
What Classes and Objects Are
Prerequisites
You should know Python functions, arguments, return values, strings, lists, dictionaries, basic control flow, and how to run Python 3 code.
Classes and Instances
A class is a definition for a new type. It describes the data and behavior that its objects can have. An object, also called an instance, is a concrete value created from a class.
For example, Dog is a class. Each dog, such as Rex or Luna, is an instance of that class. Instances of one class share the same structure, but their stored data can differ.
Initializing Objects with `__init__` and `self`
The __init__ method runs automatically when you create an instance. It initializes the instance's state, meaning the data it stores.
self refers to the particular instance currently being used. Python passes it automatically when you call an instance method, but you write it explicitly in the method definition.
class Dog:
species = "Canis familiaris"
def __init__(self, name, age):
self.name = name
self.age = age
def describe(self):
return f"{self.name} is {self.age} years old"
rex = Dog("Rex", 3)
print(rex.describe())
print(rex.species)The call Dog("Rex", 3) creates an object and passes name and age to __init__. Assignments such as self.name create attributes belonging to that object.
Instance and Class Attributes
An instance attribute belongs to one object. Rex's name can differ from Luna's name.
A class attribute belongs to the class and can be shared or used as a default by all instances. species is the same for every Dog.
| Attribute kind | Stored on | Typical use |
|---|---|---|
| Instance attribute | One object | A dog's name |
| Class attribute | The class | A shared species label |
Behavior with Instance Methods
An instance method is a function defined inside a class. It receives self, reads or changes that instance's state, and describes what the object can do. Call it with dot notation, such as rex.describe().
Exercise
What does self identify in rex.describe()?
Show answer
It identifies the Rex instance, so the method reads Rex's own attributes.