QUICK REFERENCE

Python OOP Cheat Sheet

The essential syntax, patterns, and magic methods every Python engineer needs at their fingertips.

Basics

Class Anatomy

The fundamental structure of a Python class.

class Dog:
species = "Canis" # Class Var
def __init__(self, name):
self.name = name # Instance Var
def bark(self):
return f"{self.name} says Woof!"
Core

Magic (Dunder) Methods

Special methods that start/end with double underscores.

class Vector:
def __init__(self, x, y):
self.x = x
self.y = y
def __str__(self):
return f"({self.x}, {self.y})"
def __add__(self, other):
return Vector(self.x + other.x, self.y + other.y)
Encapsulation

Access Control

Python uses naming conventions for access control.

class Account:
def __init__(self):
self.public = "Open"
self._protected = "Use with caution"
self.__private = "No touchy"
# Access private via name mangling:
# _Account__private
Encapsulation

Getters & Setters

Use the @property decorator for pythonic getters/setters.

class Celsius:
def __init__(self, temp=0):
self._temp = temp
@property
def temp(self):
return self._temp
@temp.setter
def temp(self, value):
if value < -273: raise ValueError
self._temp = value
Inheritance

Inheritance & Super

Extending classes and accessing parent methods.

class Animal:
def speak(self): print("...")
class Dog(Animal):
def speak(self):
super().speak() # Call parent
print("Woof!")
Advanced

Method Types

Instance vs Class vs Static methods.

class Demo:
def instance_m(self):
pass # Can access self
@classmethod
def class_m(cls):
pass # Can access cls state
@staticmethod
def static_m():
pass # Isolated function
Abstraction

Abstract Classes

Enforcing interfaces using the abc module.

from abc import ABC, abstractmethod
class Shape(ABC):
@abstractmethod
def area(self):
pass
# Error: Can't instantiate Shape
# Subclasses MUST implement area()
Optimization

__slots__ Optimization

Save memory by preventing dynamic attribute creation.

class Point:
__slots__ = ['x', 'y']
def __init__(self, x, y):
self.x = x
self.y = y
# self.z = 10 <-- Error!
Modern Python

Data Classes

Auto-generate __init__, __repr__ for data holders.

from dataclasses import dataclass
@dataclass
class User:
id: int
username: str
email: str = None
u = User(1, "admin")
print(u) # User(id=1, username='admin', ...)