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
Class or Static Variables in Python?
In this article we are going to learn about class or static variables in Python. The class variables or static variables are used to share data across all the instances of a class. Unlike instance variables which are specific to each object, class variables maintain a common value for all objects of the class.
They are defined within the class but outside any instance methods, making them accessible to all instances. These variables are used when we want to have a single shared state or value among all instances.
Syntax
class ClassName:
class_variable = value # Defined at class level
def __init__(self):
self.instance_variable = value # Instance-specific
Example 1: Counting Objects Created
Let's look at the following example, where we demonstrate how class variables can be used to count the objects created ?
class Demo:
count = 0
def __init__(self, name):
self.name = name
Demo.count += 1
x1 = Demo("Ravi")
x2 = Demo("Suresh")
print("Total objects created:", Demo.count)
The output of the above program is ?
Total objects created: 2
Example 2: Shared Configuration Value
Consider the following example, where we illustrate how class variables provide a shared configuration value across different objects ?
class Student:
course = "B.tech"
def __init__(self, name):
self.name = name
x1 = Student("Sunil")
x2 = Student("Poorna")
print("Student 1 course:", x1.course)
print("Student 2 course:", x2.course)
The output of the above program is ?
Student 1 course: B.tech Student 2 course: B.tech
Example 3: Modifying Class Variables
In the following example, we modify the class variable from outside the class, affecting all instances ?
class Vehicle:
engine_type = "2stroke"
def __init__(self, model):
self.model = model
print("Initial engine type:", Vehicle.engine_type)
# Modify class variable
Vehicle.engine_type = "4stroke"
v1 = Vehicle("Ciaz")
print("After modification:", v1.engine_type)
The output of the above program is ?
Initial engine type: 2stroke After modification: 4stroke
Key Points
- Class variables are shared among all instances of a class
- They are defined at the class level, not inside methods
- Access using
ClassName.variableorinstance.variable - Modifying through the class name affects all instances
- Useful for constants, counters, and shared configuration
Conclusion
Class variables in Python provide a way to share data across all instances of a class. They are perfect for maintaining counters, shared configurations, or any data that should be common to all objects of the class.
