Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
How do I create static class data and static class methods in Python?
Python provides support for static class data (class attributes) and static class methods through class variables and the @staticmethod decorator.
Static Class Data
Class attributes are shared among all instances of the class. Define them at the class level and access them using the class name ?
class Demo:
count = 0 # Static class data
def __init__(self):
Demo.count = Demo.count + 1
def getcount(self):
return Demo.count
# Create instances
obj1 = Demo()
obj2 = Demo()
obj3 = Demo()
print("Total objects created:", obj1.getcount())
print("Accessing via class:", Demo.count)
Total objects created: 3 Accessing via class: 3
Important Note About Assignment
When modifying static class data, always use the class name. Using self.count = 42 creates a new instance variable instead of modifying the class variable ?
class Demo:
count = 0
def wrong_way(self):
self.count = 42 # Creates instance variable
def right_way(self):
Demo.count = 42 # Modifies class variable
obj = Demo()
print("Before:", Demo.count)
obj.wrong_way()
print("After wrong_way:", Demo.count) # Still 0
print("Instance variable:", obj.count) # 42
obj.right_way()
print("After right_way:", Demo.count) # 42
Before: 0 After wrong_way: 0 Instance variable: 42 After right_way: 42
Static Class Methods
Static methods are bound to the class, not instances. They cannot access class or instance state and are used for utility functions. Use the @staticmethod decorator ?
class MathUtils:
@staticmethod
def add(x, y):
return x + y
@staticmethod
def is_even(number):
return number % 2 == 0
# Call static methods without creating instances
print("Addition:", MathUtils.add(5, 3))
print("Is 10 even?", MathUtils.is_even(10))
print("Is 7 even?", MathUtils.is_even(7))
# Can also call from instances (but not recommended)
utils = MathUtils()
print("From instance:", utils.add(2, 4))
Addition: 8 Is 10 even? True Is 7 even? False From instance: 6
Complete Example
Here's a practical example combining static data and methods ?
from datetime import date
class Student:
total_students = 0 # Static class data
def __init__(self, name, age):
self.name = name
self.age = age
Student.total_students += 1
@classmethod
def from_birth_year(cls, name, birth_year):
age = date.today().year - birth_year
return cls(name, age)
@staticmethod
def is_adult(age):
return age >= 18
@staticmethod
def get_total_students():
return Student.total_students
# Creating students
st1 = Student('Alice', 20)
st2 = Student('Bob', 17)
st3 = Student.from_birth_year('Charlie', 2000)
print(f"Total students: {Student.get_total_students()}")
print(f"Alice is adult: {Student.is_adult(st1.age)}")
print(f"Bob is adult: {Student.is_adult(st2.age)}")
print(f"Charlie's age: {st3.age}")
Total students: 3 Alice is adult: True Bob is adult: False Charlie's age: 24
Key Differences
| Feature | Static Data | Static Method |
|---|---|---|
| Access | Class.attribute or instance.attribute | Class.method() or instance.method() |
| Modification | Must use Class.attribute | Cannot modify class/instance state |
| Parameters | N/A | No self or cls parameter |
| Use Case | Shared data across instances | Utility functions |
Conclusion
Static class data provides shared variables across all instances, while static methods offer utility functions independent of class state. Always use the class name when modifying static data to avoid creating instance variables.
