Ad space (banner)
🐍Python Lessons
Lesson 56 / 69

Class Variables and @staticmethod Basics

This lesson covers class variables and @staticmethod, so you can work with data shared across a class rather than tied to a single instance. It's written for anyone searching "Python staticmethod tutorial".

A variable written inside a class but outside __init__ is called a "class variable," and it's shared by every instance. A method marked with @staticmethod can be called without ever creating an instance. The key difference from a regular method is that you call it directly as ClassName.method_name(), with no instance creation needed.

The sample code defines a shared counter, count = 0, on a Counter class, along with a shared operation, increment(), marked with @staticmethod. Watching Counter.count increase every time you call Counter.increment() shows that the class itself can hold state, with no instance required.

A common beginner mistake is confusing a regular method with a staticmethod. A regular method requires self as its first parameter; a staticmethod doesn't. There's also a similar decorator, @classmethod, used when you want the class itself passed in as an argument.

Once you can distinguish between per-instance values and values shared across the whole class, you can handle more sophisticated class designs. It's a mindset also put to use in real work — managing configuration values, counting instances, and more.

Python
OUTPUT

💡 The Python engine may take a few seconds to load the first time you run code.

Ad space (banner)
Ad space (in-article)