Python Tutorial · Object-Oriented Python · Lesson 27 of 42

Python Classes and Objects

Define classes, create objects and use __init__, methods and __str__.

Creating a class

A class is a blueprint; objects are instances of it. __init__ runs when an object is created, and self refers to the object itself.

Example 1Try it yourself
class Dog:
    def __init__(self, name, age):
        self.name = name
        self.age = age

    def bark(self):
        return f"{self.name} says woof!"

rex = Dog("Rex", 3)
print(rex.name, rex.age)
print(rex.bark())

Output

Rex 3
Rex says woof!

Instance vs class attributes

Attributes set on self belong to one object. Attributes defined in the class body are shared by all instances.

Example 2Try it yourself
class Counter:
    total_created = 0   # class attribute

    def __init__(self):
        self.value = 0   # instance attribute
        Counter.total_created += 1

a, b = Counter(), Counter()
a.value += 5
print(a.value, b.value, Counter.total_created)

Output

5 0 2

Special methods

Methods with double underscores customise built-in behaviour: __str__ for print(), __repr__ for debugging, __eq__ for ==, __len__ for len().

Example 3Try it yourself
class Point:
    def __init__(self, x, y):
        self.x, self.y = x, y

    def __str__(self):
        return f"({self.x}, {self.y})"

    def __eq__(self, other):
        return isinstance(other, Point) and (self.x, self.y) == (other.x, other.y)

print(Point(1, 2))
print(Point(1, 2) == Point(1, 2))

Output

(1, 2)
True

Test yourself

Which method runs automatically when a new object is created?

  1. __new__
  2. __init__
  3. __create__
  4. __start__
Show answer

Answer: __init__