Python OOP Cheat Sheet: Classes, Inheritance, Dunder Methods
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
| Task | Code | Result |
|---|---|---|
| Create an object | Account("Ravi").owner | 'Ravi' |
| Read an attribute | a.owner | 'Asha' |
| Call a method | a.deposit(50) | 150 |
| Attribute with a default | Account("Ravi")._balance | 0 |
| Type of an object | type(a).__name__ | 'Account' |
| Is it an instance? | isinstance(a, Account) | True |
| Add an attribute later | a.vip = True; a.vip | True |
| Check for an attribute | hasattr(a, "owner"), hasattr(a, "nope") | (True, False) |
| Missing attribute raises | a.nope | AttributeError: 'Account' object has no attribute 'nope' |
| Instance attributes as a dict | vars(Account("Zed", 5)) | {'owner': 'Zed', '_balance': 5} |
| Function vs method | type(Account.deposit).__name__, type(a.deposit).__name__ | ('function', 'method') |
Python class attributes, classmethod and staticmethod
| Task | Code | Result |
|---|---|---|
| Class attribute shared by all | Account.bank | 'PyBank' |
| Read it through an instance | a.bank | 'PyBank' |
| Class-level counter | Account.count | 1 |
| Alternative constructor | Account.from_text("Meera:80").owner | 'Meera' |
| classmethod receives the class | Account.from_text("Meera:80")._balance | 80 |
| staticmethod: no self or cls | Account.is_valid(-5) | False |
| Static method via instance | a.is_valid(5) | True |
| Instance attribute shadows class one | a.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 class | type(Account).__name__ | 'type' |
Python dunder (magic) methods cheat sheet
| Task | Code | Result |
|---|---|---|
| str for print() | str(a) | 'Asha: 100' |
| repr for debugging | repr(a) | "Account('Asha', 100)" |
| eq for == | a == Account("Asha", 100) | True |
| len for len() | len(a) | 100 |
| init runs on creation | Account("Ravi", 9)._balance | 9 |
| Default equality compares identity | object() == object() | False |
| add for + | Money(2) + Money(3) | Money(5) when the class defines __add__ |
| lt for sorting | sorted([Num(3), Num(1)]) | sorts by whatever __lt__ defines |
| f-string uses format or str | f"{a}" | 'Asha: 100' |
| getitem for a[i] | Box()[0] | indexing calls __getitem__ |
Python inheritance, polymorphism and composition cheat sheet
| Task | Code | Result |
|---|---|---|
| Subclass is an instance of parent | isinstance(s, Account) | True |
| Subclass check | issubclass(Savings, Account) | True |
| Inherited attribute | s.owner | 'Meera' |
| Override a method and call super() | s.deposit(10) | 211 |
| Parent method unchanged | Account("X", 0).deposit(10) | 10 |
| New attribute in the subclass | s.rate | 0.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 built | Shape() | TypeError: Can't instantiate abstract class Shape without an implementation for abstract method 'area' |
| Composition: has-a | Wrapper().acct.owner | 'Ana' (an object holds another object) |
| Check method existence | callable(getattr(s, "deposit", None)) | True |
Python properties, encapsulation and dataclasses
| Task | Code | Result |
|---|---|---|
| Read a property like an attribute | a.balance | 100 |
| Property is read-only without a setter | a.balance = 5 | AttributeError: property 'balance' of 'Account' object has no setter |
| Convention: underscore means internal | a._balance | 100 |
| Name mangling with double underscore | Secret().__dict__ | {'_Secret__pin': 1} |
| Dataclass repr for free | Point(1, 2) | Point(x=1, y=2) |
| Dataclass default | Point(5) | Point(x=5, y=0) |
| Dataclass equality | Point(1, 2) == Point(1, 2) | True |
| Dataclass to dict | vars(Point(3, 4)) | {'x': 3, 'y': 4} |
| Frozen dataclass | FP(1).x | 1; assigning later raises FrozenInstanceError |
| slots limits attributes | Tiny().__slots__ | ('a',) |
Python OOP terms explained in one line each
| Task | Code | Result |
|---|---|---|
| Class | class Dog: ... | a blueprint that describes attributes and methods |
| Object (instance) | d = Dog() | one concrete thing built from the class |
| self | def bark(self): ... | the instance the method is called on, passed automatically |
| init | def __init__(self, name): ... | runs when an instance is created; sets up attributes |
| Inheritance | class Puppy(Dog): ... | a subclass reuses and extends a parent class |
| super() | super().__init__(name) | calls the parent version of a method |
| Polymorphism | for pet in pets: pet.speak() | one call works on many types that share a method name |
| Encapsulation | self._balance | keep internal data behind methods or properties |
| Abstract class | class Shape(ABC): ... | defines methods subclasses must implement |
| Dataclass | @dataclass | generates __init__, __repr__ and __eq__ from annotations |
| Mixin / multiple inheritance | class 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 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.
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 →