Classes and Objects

The big idea

So far, data (variables) and actions (functions) have lived separately. A class lets you bundle them together into your own new type of thing.

Think of it like this: A class is a blueprint for a house. An object is a real house built from it. From one blueprint you can build many houses, each with its own paint colour and owner.

You've used objects all along: every string is an object of the str class, which is why it has methods like upper().

Your first class

class Dog:
    def __init__(self, name, age):
        self.name = name
        self.age = age

my_dog = Dog("Bruno", 3)
your_dog = Dog("Moti", 5)
print(my_dog.name, "is", my_dog.age)
print(your_dog.name, "is", your_dog.age)

Output

Bruno is 3
Moti is 5

Let's unpack it:

  • class Dog: creates the blueprint. Class names start with a capital letter.
  • __init__ (two underscores on each side) is a special method that runs automatically when you create a new object. It sets the object up.
  • self means “this particular object”. self.name = name stores the name inside the object.
  • Dog("Bruno", 3) creates (or builds) a new Dog object.

Values stored on self are called attributes. Each object keeps its own.

Remember: Every method in a class takes self as its first parameter, but you don't pass it yourself – Python does that for you.

HOME LEARN COMMUNITY DASHBOARD