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

More Python tasks

Back to the full Python cheat sheet