class
Defines a class: a template for objects that combines data with the functions that act on it.
Example
#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)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
#class Name:
def __init__(self, param):
self.attribute = param
def method(self):
...More examples
#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())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
#- defDefines a function: a named block of code with parameters that you can call multiple times.
- importLoads a module, or selected names from a module, into the current file.
- withA context manager: automatic setup and cleanup of resources.
- isinstance()Checks whether an object is of a given type, or of a subtype of it.
- __init__()A method called automatically when an object is created. It stores the object’s initial data, its attributes.
- InheritanceBuilding one class on top of another: the derived class inherits the base class’s methods and can extend or override them.
Spotted a mistake or missing an example? Write to us.