Class

A blueprint for creating objects that bundle data (attributes) with behaviour (methods).

A class defines a new type. You write it once with the class keyword, then create as many objects from it as you like. The special __init__ method runs automatically when each object is created and sets up its starting attributes via self.

Functions defined inside a class are its methods — behaviour that lives with the data. Grouping data and behaviour together is the core idea of object-oriented programming.

Example
class Dog:
    def __init__(self, name):
        self.name = name          # an attribute

    def speak(self):              # a method
        return f"{self.name} says woof"

rex = Dog("Rex")                  # create an object
print(rex.speak())
Output
Rex says woof

Where this shows up in real Python

Classes model real things — a User, an Account, a Report — bundling related data and the behaviour that goes with it.

Commonly used Class tools

  • def __init__(self, ...) — set up each new instance
  • self — the current instance inside a method
  • Account(100) — call the class to create an object
  • isinstance(obj, Account) — check an object’s type

Official documentation: Python Tutorial: Classes