Object-oriented programming · 1 / 26 Theory

Classes and objects

Python is an object-oriented language. This paradigm organizes programs around two fundamental concepts: classes and objects.

  • A class is a template that defines the data and the behavior of a kind of thing.
  • An object (or *instance*) is a specific thing created from a class.

For example, Dog is a class and your neighbor's dog "Rex" is an object of that class.

Defining a class

A class is defined with the class keyword. Class names use CamelCase:

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

    def bark(self):
        print(f"{self.name} says woof!")
  • __init__ is the constructor, it runs when the object is created.
  • self is the object itself. It is always the first parameter of a method.

Creating objects

To create an object you call the class as if it were a function. There is no new keyword:

rex = Dog("Rex", 3)
luna = Dog("Luna", 5)

print(rex.name)    # Rex
luna.bark()        # Luna says woof!

Each object has its own data: changing rex.age does not change luna.age.

Printing an object

By default, printing an object shows something like <__main__.Dog object at 0x...>. You can define the special method __str__ to control the text:

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

    def __str__(self):
        return f"Dog named {self.name}"

print(Dog("Rex"))   # Dog named Rex

Why use classes?

Classes group data and the functions that work with it, avoid repeating code and make big programs easier to organize, test and reuse.