A blueprint for your own type
A class describes the data and the behaviour of something. An object built from it is an instance.
class Dog:
def __init__(self, name, age):
self.name = name
self.age = age
def speak(self):
return f"{self.name} says woof"
rex = Dog("Rex", 3) # create an instance
print(rex.name) # Rex
print(rex.speak()) # Rex says woof
What is self?
self is the instance the method is working on — Python passes it in for you. __init__ is the setup that runs when an object is created, and it is where attributes are stored (self.name = name).
Methods are just functions that live inside a class, and every method's first parameter is self. Two separate objects each keep their own attributes:
a = Dog("Ada", 3)
b = Dog("Pixel", 1)
print(a.name) # Ada
print(b.name) # Pixel
Classes are how you keep data and the operations on that data together — the shape most real Python code is built from.