Python OOP and Modules

Classes, dataclasses, inheritance, properties, abstract base classes, modules, and package patterns.

View
StandardDetailedCompact
Export
Copy the compact sheet, download it, or print it.
Download
`D` dense toggle · `C` copy all
## Classes and instances
Basic class
class User:
    def __init__(self, name: str):
        self.name = name

# Basic class

Instance method
class User:
    def greet(self) -> str:
        return f"Hello, {self.name}"

# Instance method

Class variable
class Job:
    queue = "default"

# Class variable

Class method
class User:
    @classmethod
    def from_dict(cls, data: dict):
        return cls(data["name"])

# Class method

Static method
class Math:
    @staticmethod
    def clamp(value, low, high):
        return max(low, min(value, high))

# Static method

Dataclass
from dataclasses import dataclass

@dataclass
class Point:
    x: int
    y: int

# Dataclass

## Inheritance and protocols
Subclass
class Admin(User):
    def can_delete(self) -> bool:
        return True

# Subclass

Call super
class Child(Base):
    def __init__(self, name: str):
        super().__init__(name)

# Call super

Property getter/setter
class Celsius:
    def __init__(self, value: float):
        self._value = value

    @property
    def value(self) -> float:
        return self._value

    @value.setter
    def value(self, new_value: float):
        self._value = new_value

# Property getter/setter

ABC abstract method
from abc import ABC, abstractmethod

class Shape(ABC):
    @abstractmethod
    def area(self) -> float:
        raise NotImplementedError

# ABC abstract method

## Modules and imports
Import a module
import math
radius = math.sqrt(49)

# Import a module

Import a name
from pathlib import Path

# Import a name

Import with alias
import numpy as np

# Import with alias

Guard script entry point
def main():
    print("running")

if __name__ == "__main__":
    main()

# Guard script entry point

Module docstring
"""Utility helpers for report generation."""

# Module docstring

Package __init__
__all__ = ["connect", "disconnect"]

# Package __init__