Cheat sheetCore Python

Python OOP Cheat Sheet: Classes, Inheritance, Dunder Methods

Short answer
In Python OOP you define a class as a blueprint, build objects with it, store data in attributes set in __init__, share behaviour through methods and inheritance, and customise built-in behaviour with dunder methods.

Object-oriented programming bundles data and the functions that work on it into classes. This cheat sheet covers the pieces you use daily: classes and instances, class attributes, @classmethod and @staticmethod, dunder methods, inheritance, properties and dataclasses. Results were produced by running the code on Python 3.13.

Background lessons: classes and objects, inheritance and dunder methods.

The tables reuse one small Account example so you can follow how the pieces fit together:

class Account:
    bank = "PyBank"
    def __init__(self, owner, balance=0):
        self.owner = owner
        self._balance = balance
    def deposit(self, amount):
        self._balance += amount
        return self._balance
    @property
    def balance(self):
        return self._balance

Python class and object basics cheat sheet

Assume the `Account` class from the intro, extended with a class attribute `count`, `from_text`, `is_valid`, `__str__`, `__repr__`, `__eq__` and `__len__`, plus subclasses `Savings`, `Square(Shape)` and a `Point` dataclass, and `a = Account("Asha", 100)`.
TaskCodeResult
Create an objectAccount("Ravi").owner'Ravi'
Read an attributea.owner'Asha'
Call a methoda.deposit(50)150
Attribute with a defaultAccount("Ravi")._balance0
Type of an objecttype(a).__name__'Account'
Is it an instance?isinstance(a, Account)True
Add an attribute latera.vip = True; a.vipTrue
Check for an attributehasattr(a, "owner"), hasattr(a, "nope")(True, False)
Missing attribute raisesa.nopeAttributeError: 'Account' object has no attribute 'nope'
Instance attributes as a dictvars(Account("Zed", 5)){'owner': 'Zed', '_balance': 5}
Function vs methodtype(Account.deposit).__name__, type(a.deposit).__name__('function', 'method')

Python class attributes, classmethod and staticmethod

Assume the `Account` class from the intro, extended with a class attribute `count`, `from_text`, `is_valid`, `__str__`, `__repr__`, `__eq__` and `__len__`, plus subclasses `Savings`, `Square(Shape)` and a `Point` dataclass, and `a = Account("Asha", 100)`.
TaskCodeResult
Class attribute shared by allAccount.bank'PyBank'
Read it through an instancea.bank'PyBank'
Class-level counterAccount.count1
Alternative constructorAccount.from_text("Meera:80").owner'Meera'
classmethod receives the classAccount.from_text("Meera:80")._balance80
staticmethod: no self or clsAccount.is_valid(-5)False
Static method via instancea.is_valid(5)True
Instance attribute shadows class onea.bank = "Other"; (a.bank, Account.bank)('Other', 'PyBank')
List all attribute names[n for n in vars(a)]['owner', '_balance']
Check the class of a classtype(Account).__name__'type'

Python dunder (magic) methods cheat sheet

Assume the `Account` class from the intro, extended with a class attribute `count`, `from_text`, `is_valid`, `__str__`, `__repr__`, `__eq__` and `__len__`, plus subclasses `Savings`, `Square(Shape)` and a `Point` dataclass, and `a = Account("Asha", 100)`.
TaskCodeResult
str for print()str(a)'Asha: 100'
repr for debuggingrepr(a)"Account('Asha', 100)"
eq for ==a == Account("Asha", 100)True
len for len()len(a)100
init runs on creationAccount("Ravi", 9)._balance9
Default equality compares identityobject() == object()False
add for +Money(2) + Money(3)Money(5) when the class defines __add__
lt for sortingsorted([Num(3), Num(1)])sorts by whatever __lt__ defines
f-string uses format or strf"{a}"'Asha: 100'
getitem for a[i]Box()[0]indexing calls __getitem__

Python inheritance, polymorphism and composition cheat sheet

Also assume `s = Savings("Meera", 200)`.
TaskCodeResult
Subclass is an instance of parentisinstance(s, Account)True
Subclass checkissubclass(Savings, Account)True
Inherited attributes.owner'Meera'
Override a method and call super()s.deposit(10)211
Parent method unchangedAccount("X", 0).deposit(10)10
New attribute in the subclasss.rate0.04
Method resolution order[c.__name__ for c in Savings.__mro__]['Savings', 'Account', 'object']
Same call, different classes[x.area() for x in (Square(2), Square(3))][4, 9]
Abstract class cannot be builtShape()TypeError: Can't instantiate abstract class Shape without an implementation for abstract method 'area'
Composition: has-aWrapper().acct.owner'Ana' (an object holds another object)
Check method existencecallable(getattr(s, "deposit", None))True

Python properties, encapsulation and dataclasses

TaskCodeResult
Read a property like an attributea.balance100
Property is read-only without a settera.balance = 5AttributeError: property 'balance' of 'Account' object has no setter
Convention: underscore means internala._balance100
Name mangling with double underscoreSecret().__dict__{'_Secret__pin': 1}
Dataclass repr for freePoint(1, 2)Point(x=1, y=2)
Dataclass defaultPoint(5)Point(x=5, y=0)
Dataclass equalityPoint(1, 2) == Point(1, 2)True
Dataclass to dictvars(Point(3, 4)){'x': 3, 'y': 4}
Frozen dataclassFP(1).x1; assigning later raises FrozenInstanceError
slots limits attributesTiny().__slots__('a',)

Python OOP terms explained in one line each

TaskCodeResult
Classclass Dog: ...a blueprint that describes attributes and methods
Object (instance)d = Dog()one concrete thing built from the class
selfdef bark(self): ...the instance the method is called on, passed automatically
initdef __init__(self, name): ...runs when an instance is created; sets up attributes
Inheritanceclass Puppy(Dog): ...a subclass reuses and extends a parent class
super()super().__init__(name)calls the parent version of a method
Polymorphismfor pet in pets: pet.speak()one call works on many types that share a method name
Encapsulationself._balancekeep internal data behind methods or properties
Abstract classclass Shape(ABC): ...defines methods subclasses must implement
Dataclass@dataclassgenerates __init__, __repr__ and __eq__ from annotations
Mixin / multiple inheritanceclass C(A, B): ...a class with more than one parent, resolved by the MRO

Examples you can run

Press Run, then edit the code and run it again.

Class, property and classmethod together

An Account with a read-only property and an alternative constructor.

Class, property and classmethod together
class Account:
    def __init__(self, owner, balance=0):
        self.owner = owner
        self._balance = balance

    @property
    def balance(self):
        return self._balance

    @classmethod
    def from_text(cls, text):
        name, amount = text.split(":")
        return cls(name, int(amount))

    def __str__(self):
        return f"{self.owner} has {self._balance}"

acct = Account.from_text("Asha:250")
print(acct)
print(acct.balance)
Expected outputAsha has 250
250

Inheritance and polymorphism

Each subclass overrides speak(); the loop does not care which class it gets.

Inheritance and polymorphism
class Animal:
    def __init__(self, name):
        self.name = name
    def speak(self):
        return "..."

class Dog(Animal):
    def speak(self):
        return f"{self.name} says Woof"

class Cat(Animal):
    def speak(self):
        return f"{self.name} says Meow"

for pet in (Dog("Rex"), Cat("Tom"), Animal("Generic")):
    print(pet.speak())
Expected outputRex says Woof
Tom says Meow
...

Python OOP Cheat Sheet: Classes, Inheritance, Dunder Methods: questions people ask

What does self mean in Python classes?

self is the instance a method is working on. Python passes it automatically as the first argument, so a.deposit(5) is the same as Account.deposit(a, 5).

What is the difference between a classmethod and a staticmethod?

A @classmethod receives the class as cls and is often used for alternative constructors, while a @staticmethod receives neither self nor cls and behaves like a plain function stored in the class.

When should I use a dataclass instead of a normal class?

Use @dataclass when the class mainly holds data. It generates __init__, __repr__ and __eq__ from the annotated fields, so you write far less boilerplate.

Keep learning

Step-by-step lessons:
Python Classes and ObjectsPython InheritancePython Dunder (Magic) Methods

Related:
Python Cheat Sheet (Python 3.13 Quick Reference)Python Functions Cheat Sheet: def, args, lambda, scopePython @staticmethod vs @classmethod: What Is the Difference?Python Function vs Method: What Is the Difference?Python Dataclasses

More in core python:
Python Cheat Sheet (Python 3.13 Quick Reference)Python String Cheat Sheet: Methods and FormattingPython List Cheat Sheet: Methods and ExamplesPython Dictionary Cheat Sheet: Methods and ExamplesPython Control Flow Cheat Sheet: if, for, while, matchPython Functions Cheat Sheet: def, args, lambda, scopePython Regex Cheat Sheet (re Module Quick Reference)Python File Handling Cheat Sheet: open, read, write, CSV, JSON See all →