Class Basics in Python
From the Python cheat sheet ยท Classes & OOP ยท verified Jul 2026
Class Basics
Define classes with __init__, instance methods, and class/static methods.
python
class Dog:
species = "Canine" # Class variable
def __init__(self, name, age):
self.name = name # Instance variable
self.age = age
def bark(self):
return f"{self.name} says woof!"
rex = Dog("Rex", 5)
rex.bark() # "Rex says woof!"๐ก Use @property to create computed attributes accessed without parentheses
โก @classmethod receives the class (cls) โ great for alternative constructors
๐ @staticmethod receives neither self nor cls โ it's just a namespaced function
๐ข Always define __repr__ for debugging โ __str__ is for user-facing output
classesoopmethods