class

Defines a class: a template for objects that combines data with the functions that act on it.

On this page

Example

#
Python
class Student:
    def __init__(self, name, level=1):
        self.name = name
        self.level = level

    def level_up(self):
        self.level += 1
        return self.level

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

emma = Student("Emma")
emma.level_up()
print(emma)
Resultsaved result, you can check it
Emma (level 2)

Definition and usage

#

The class keyword creates a new type of object. The special method __init__ sets up a new object’s data when it is created, and the first parameter of every method, conventionally named self, refers to the object the method is acting on.

Classes can inherit from other classes: class Mentor(Person) gets all of Person’s methods and can extend or override them. The super() function lets you call a method of the base class.

Methods with double underscores, like __str__ or __repr__, define how an object behaves in built-in operations, for example in print(). For simple classes that store data, the @dataclass decorator is convenient.

Syntax

#
Syntax
class Name:
    def __init__(self, param):
        self.attribute = param

    def method(self):
        ...

More examples

#
Inheritance and dataclass
Python
from dataclasses import dataclass

@dataclass
class Course:
    title: str
    modules: int

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

    def introduce(self):
        return f"I'm {self.name}"

class PythonMentor(Mentor):
    def introduce(self):
        return super().introduce() + " and I teach Python"

print(Course("Python", 12))
print(PythonMentor("Darwin").introduce())
Resultsaved result, you can check it
Course(title='Python', modules=12)
I'm Darwin and I teach Python

Good practices

#
  • Write class names in PascalCase (StudentProfile), and method and field names in snake_case.
  • For classes that mainly store data, use @dataclass. You get __init__, __repr__, and comparisons automatically.

Related entries

#

Spotted a mistake or missing an example? Write to us.