Question
Python Static Variables and Methods: Class Variables, @classmethod, and @staticmethod
Question
How can I create class-level variables and methods in Python?
I want to understand how to define variables that belong to the class itself rather than to each individual object, and how to create methods that can be called on the class without requiring an instance. In other words, how do class variables, @classmethod, and @staticmethod work in Python?
Short Answer
By the end of this page, you will understand how Python stores data on a class, how class variables differ from instance variables, and how to define methods that work at the class level using @classmethod and utility-style methods using @staticmethod. You will also see when to use each one and the mistakes beginners commonly make.
Concept
In Python, the phrase static variable is usually expressed as a class variable. A class variable is defined inside the class body and is shared by all instances of that class unless an instance overrides it.
A Python class can have three common kinds of members:
- Instance variables: belong to one object
- Class variables: belong to the class itself
- Methods: functions defined inside the class
And methods themselves can be of three main types:
- Instance methods: take
selfand work with one object - Class methods: take
clsand work with the class - Static methods: take neither
selfnorclsautomatically
Why this matters
This matters because real programs often need:
- shared configuration across all objects
- counters that track how many objects were created
- factory methods that construct objects in a standard way
- utility functions that logically belong inside a class
Class variables
A class variable is defined directly in the class:
class User:
role = "member"
Here, role belongs to , not to any one object.
Mental Model
Think of a class as a building blueprint.
- An instance variable is furniture inside one specific apartment.
- A class variable is a sign posted on the building entrance that everyone in the building can see.
- An instance method is something one resident does inside their own apartment.
- A class method is something the building manager does for the whole building.
- A static method is like a rule sheet stored in the lobby: it belongs there, but it does not depend on any specific resident or even the manager.
So if data or behavior applies to the whole class, put it on the class. If it applies to one object, put it on the instance.
Syntax and Examples
Core syntax
Class variable
class Dog:
species = "Canis familiaris"
Instance variable
class Dog:
def __init__(self, name):
self.name = name
Class method
class Dog:
count = 0
@classmethod
def get_count(cls):
return cls.count
Static method
class Dog:
@staticmethod
def is_valid_name(name):
return len(name) > 0
Example: class variable and instance variable together
Step by Step Execution
Consider this example:
class Product:
tax_rate = 0.1
def __init__(self, name, price):
self.name = name
self.price = price
def total_price(self):
return self.price + (self.price * Product.tax_rate)
Now run:
p = Product("Book", 20)
print(p.total_price())
Step by step
1. Python reads the class definition
class Product:
Python creates the Product class object.
2. Python stores the class variable
tax_rate = 0.1
This value is attached to the class itself.
3. Python stores the methods
Real World Use Cases
Shared settings
class AppConfig:
debug = True
version = "1.0"
Useful for values shared across the application.
Object counters
class Session:
active_sessions = 0
def __init__(self):
Session.active_sessions += 1
Useful for tracking how many objects have been created.
Factory methods
class User:
def __init__(self, username, active=True):
self.username = username
self.active = active
@classmethod
def guest(cls):
return cls("guest", active=False)
Useful when you want alternate ways to create objects.
Validation helpers
Real Codebase Usage
In real projects, developers commonly use these patterns:
Class variables for shared constants
class HTTPStatus:
OK = 200
NOT_FOUND = 404
These values are shared and do not change per instance.
Class methods as alternative constructors
class User:
def __init__(self, name, age):
self.name = name
self.age = age
@classmethod
def from_string(cls, text):
name, age = text.split(",")
return cls(name, int(age))
This pattern is common for parsing files, config values, or API input.
Guard clauses with validation
class User:
@staticmethod
def is_valid_age(age):
return age >= 0
def ():
.is_valid_age(age):
ValueError()
.name = name
.age = age
Common Mistakes
Mistake 1: Modifying a class variable through an instance by accident
class Item:
count = 0
item1 = Item()
item2 = Item()
item1.count = 5
print(item1.count) # 5
print(item2.count) # 0
print(Item.count) # 0
Why this happens
item1.count = 5 creates a new instance variable on item1. It does not change the class variable.
Better approach
Item.count = 5
or inside a class method:
@classmethod
def set_count(cls, value):
cls.count = value
Mistake 2: Using mutable class variables unintentionally
class Basket:
items = []
All instances share the same list, which is often not what beginners expect.
Broken behavior
Comparisons
| Concept | Uses self? | Uses cls? | Access instance data? | Access class data? | Common use |
|---|---|---|---|---|---|
| Instance method | Yes | No | Yes | Yes | Work with one object |
| Class method | No | Yes | No | Yes | Shared behavior, alternate constructors |
| Static method | No | No | No | No, unless referenced manually | Utility function related to class |
Class variable vs instance variable
Cheat Sheet
Quick reference
Class variable
class MyClass:
shared_value = 10
- Shared by all instances
- Access with
MyClass.shared_value - Can also be read through instances
Instance variable
class MyClass:
def __init__(self, value):
self.value = value
- Separate for each object
Class method
class MyClass:
@classmethod
def my_method(cls):
return cls
- Receives the class as
cls - Useful for shared logic and factory methods
Static method
class MyClass:
():
x + y
FAQ
What is the Python equivalent of a static variable?
In Python, the equivalent is usually a class variable, defined directly inside the class body.
How do I create a static method in Python?
Use the @staticmethod decorator:
class Example:
@staticmethod
def hello():
return "hello"
What is the difference between @classmethod and @staticmethod in Python?
A class method receives cls and can access class state. A static method receives no automatic argument and behaves like a regular function stored inside the class.
Can a class method change a class variable?
Yes. That is one of its main uses.
@classmethod
def set_value(cls, value):
cls.some_value = value
Can an instance access a class variable?
Yes. An instance can read a class variable unless that name is overridden on the instance itself.
Why does changing a class list affect all objects?
Because a mutable class variable, like a list or dictionary, is shared by all instances.
Mini Project
Description
Build a small BankAccount class to practice class variables, class methods, and static methods together. This project demonstrates a realistic pattern: tracking shared information across all accounts, creating objects in different ways, and validating input with helper logic.
Goal
Create a Python class that tracks the number of bank accounts, stores per-account data, and provides a utility method for validating deposit amounts.
Requirements
- Create a
BankAccountclass with an account holder name and balance. - Add a class variable that counts how many accounts have been created.
- Add a class method that returns the total number of accounts.
- Add a static method that checks whether a deposit amount is valid.
- Add a
deposit()instance method that uses the validation logic.
Keep learning
Related questions
@staticmethod vs @classmethod in Python Explained
Learn the difference between @staticmethod and @classmethod in Python with clear examples, use cases, mistakes, and a mini project.
Catch Multiple Exceptions in One except Block in Python
Learn how to catch multiple exceptions in one Python except block using tuples, with examples, mistakes, and real-world usage.
Convert Bytes to String in Python 3
Learn how to convert bytes to str in Python 3 using decode(), text mode, and proper encodings with practical examples.