Static in Python
In Python, the term static is commonly associated with the keyword static in other programming languages like Java or C++, but Python doesn’t have a direct static keyword. Instead, static behavior is typically achieved using class variables and static methods.
Let’s dive into the details of this concept:
1. Static Variables (Class Variables)
Class variables in Python are the names used for static variables. They are common to all instances (objects) of a class. In other words, unlike instance variables that are specific to an object, class variables are common to all instances of the class.
Features:
- A class variable is like a shared resource that you create in a class, and it’s not tied to any particular method.
- All instances of the class share the same value of a class variable.
- Modifying a class variable affects all instances of the class.
Example:
class MyClass:
static_variable = 0 # class variable
def __init__(self, value):
self.value = value # instance variable
def increment(self):
MyClass.static_variable += 1
# Creating instances
obj1 = MyClass(10)
obj2 = MyClass(20)
# Accessing static (class) variable
print(obj1.static_variable) # Output: 0
print(obj2.static_variable) # Output: 0
obj1.increment()
print(obj1.static_variable) # Output: 1
print(obj2.static_variable) # Output: 1
Output:
0
0
1
1
static_variableis shared betweenobj1andobj2. After callingobj1.increment(), the value ofstatic_variablebecomes 1 for both objects.
2. Static Methods
A static method is like a tool that belongs to the class itself, not to any specific object or instance of that class. It cannot access instance-specific attributes (like self), but it can access class-level attributes (via the class itself). Static methods are defined using the @staticmethod decorator.
Features:
- A static method does not call for an instance to be used.
- It does not gain access to the instance variables (
self) directly unless they have been explicitly passed, nor do class variables.
Example:
class MyClass:
@staticmethod
def static_method(a, b):
return a + b
# Calling static method without creating an object
result = MyClass.static_method(5, 10)
print(result) # Output: 15
Output:
15
- The static method can be called directly through the class without needing an object. It adds
5and10and returns15.
3. Class Methods vs Static Methods
There is a difference between class methods and static methods in Python:
- A class method has access to the class itself via the
clsparameter. It can modify class-level variables. - A static method does not have access to
clsorselfand operates independently of the class state.
Example Comparison:
class MyClass:
class_variable = 0
@staticmethod
def static_method(a, b):
return a + b
@classmethod
def class_method(cls, value):
cls.class_variable += value
return cls.class_variable
# Using class method
print(MyClass.class_method(5)) # Output: 5
# Using static method
print(MyClass.static_method(3, 7)) # Output: 10
Output:
5
10
- The
class_methodmodifies the class-level variableclass_variableand returns the new value. - The
static_methodsimply adds the two passed parameters and returns the sum.
4. When to use static methods or class variables
- Class variables are used to share data among all instances of a class. Examples include a counter or a default setting.
- Static methods are useful when the class has its own functionality and doesn’t need data from instances. They are often used for utility functions that work with parameters and do not depend on class or instance data.
5. Static Classes (Not a Feature in Python)
In some languages, such as C++, a “static class” is a class that cannot be instantiated and has only static members. Python has no static class type, but you can get similar behavior with:
- A class with only static methods.
- A class with a new method that inhibits instantiation.
Example of Preventing Instantiation:
class StaticClass:
def __new__(cls):
raise TypeError("This class cannot be instantiated.")
@staticmethod
def static_method():
print("This is a static method.")
# Attempting to instantiate will raise an error
# obj = StaticClass() # TypeError: This class cannot be instantiated.
StaticClass.static_method() # This is a static method.
Output:
This is a static method.
- It would throw a
TypeErrorif you tried to instantiateStaticClass(commented out in the code). - The static method can still be called directly without an instance and still produces the output
"This is a static method.".
Summary:
- Static Variables: Common to all instances of a class (class variables).
- Static Methods: Class functions to be called by name without a particular instance of a class.
- Class Methods: These are methods that operate on the class itself and can access or modify class variables.